MongoDB Aggregateを実装します-巻き戻し、グループ化、プロジェクトしますか?
MongoDBの$unwindは、入力ドキュメントから配列フィールドを分解して、各要素のドキュメントを出力します。
$ groupは、指定された_id式によって入力ドキュメントをグループ化するために使用され、個別のグループ化ごとに、ドキュメントを出力します。
$ projectは、要求されたフィールドを持つドキュメントをパイプラインの次のステージに渡すために使用されます。
ドキュメントを使用してコレクションを作成しましょう-
> db.demo238.insertOne(
... {
...
... "EmailId" : "John@gmail.com",
... "details" : [
... {
... "Name" : "Bob",
... "isActive" : true
... }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4418e3f4cebbeaebec5152")
}
>
> db.demo238.insertOne(
... {
...
... "EmailId" : "Chris@gmail.com",
... "details" : [
... {
... "Name" : "David"
... }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4418e3f4cebbeaebec5153")
}
>
>
> db.demo238.insertOne(
... {
...
... "EmailId" : "Mike@gmail.com",
... "details" : [
... {
... "Name" : "Carol",
... "isActive" : true
... }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4418e4f4cebbeaebec5154")
} find()メソッドを使用してコレクションからすべてのドキュメントを表示します:
> db.demo238.find().pretty();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5e4418e3f4cebbeaebec5152"),
"EmailId" : "John@gmail.com",
"details" : [
{
"Name" : "Bob",
"isActive" : true
}
]
}
{
"_id" : ObjectId("5e4418e3f4cebbeaebec5153"),
"EmailId" : "Chris@gmail.com",
"details" : [
{
"Name" : "David"
}
]
}
{
"_id" : ObjectId("5e4418e4f4cebbeaebec5154"),
"EmailId" : "Mike@gmail.com",
"details" : [
{
"Name" : "Carol",
"isActive" : true
}
]
} 以下は、MongoDB Aggregateを実装するためのクエリです-アンワインド、グループ化、プロジェクト-
> db.demo238.aggregate(
... [
... { "$match": { "details.isActive": true } },
... { "$unwind": "$details" },
... { "$match": { "details.isActive": true } },
... { "$group": {
... "_id": "$details.Name",
... "active": { "$first": "$_id" }
... }}
... ],
... function(err,result) {
...
... }
...); これにより、次の出力が生成されます-
{ "_id" : "Carol", "active" : ObjectId("5e4418e4f4cebbeaebec5154") }
{ "_id" : "Bob", "active" : ObjectId("5e4418e3f4cebbeaebec5152") } -
MongoDB Aggregateを使用して、ドキュメントと配列要素の平均を取得しますか?
このために、$groupおよびaggregate()とともに$avgを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo598.insertOne( ... { ... Information:'Student', ... id:100, ... details:[ ... {Name:'Chris',Ma
-
MongoDB Aggregate groupの複数の結果?
複数の結果を集約するには、MongoDBで$groupを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo765.insertOne( ... ... { ... Name:"John", ... "Category":"ComputerScience", ... "SubjectName":"MongoDB&quo