Aggregation in MongoDB for nested documents?

MongoDBDatabaseBig Data Analytics

For aggregation in MongoDB, use aggregate(). Let us create a collection with documents −

> db.demo199.insertOne(
...   {
...      "details1":{
...         "details2":{
...            "details3":{
...               "Name":"Chris",
...               "details4":{
...                  "details5":{
...                     "v1":10,
...                     "v2":20,
...                     "v3":30
...                  }
...               }
...    }}}}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3c24aa03d395bdc21346e2")
}
>
> db.demo199.insertOne(
...   {
...      "details1":{
...         "details2":{
...            "details3":{
...               "Name":"Chris",
...               "details4":{
...                  "details5":{
...                     "v1":30,
...                     "v2":40,
...                     "v3":50
...                  }
...               }
...   }}}}
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3c24ab03d395bdc21346e3")
}

Display all documents from a collection with the help of find() method −

> db.demo199.find();

This will produce the following output −

{ "_id" : ObjectId("5e3c24aa03d395bdc21346e2"), "details1" : { "details2" : { "details3" : { "Name" : "Chris", "details4" : { "details5" : { "v1" : 10, "v2" : 20, "v3" : 30 } } } } } }
{ "_id" : ObjectId("5e3c24ab03d395bdc21346e3"), "details1" : { "details2" : { "details3" : { "Name" : "Chris", "details4" : { "details5" : { "v1" : 30, "v2" : 40, "v3" : 50 } } } } } }

Following is the query for aggregation in MongoDB for nested documents −

> var out = [
...   {
...      "$unwind": "$details1.details2"
...   },
...   {
...      "$group": {
...         "_id": "$details1.details2._id",
...         "v1": { "$sum": "$details1.details2.details3.details4.details5.v1" },
...         "v2": { "$sum": "$details1.details2.details3.details4.details5.v2" },
...         "v3": { "$sum": "$details1.details2.details3.details4.details5.v3" },
...      }
...   }
...]
> result = db.demo199.aggregate(out);

This will produce the following output −

{ "_id" : null, "v1" : 40, "v2" : 60, "v3" : 80 }
raja
Published on 27-Mar-2020 14:40:25
Advertisements