MongoDB aggregation framework with group query example?

MongoDBDatabaseBig Data Analytics

For this, use $group in MongoDB aggregation. Let us create a collection with documents −

> db.demo639.insertOne(
...    {
...       "_id" : 1,
...       "CountryName" : "US",
...       "Info1" : {
...          "Name" : "Chris",
...          "SubjectName" : "MySQL",
...          "Marks" : 78
...       },
...       "Info2" : {
...          "Name" : "Chris",
...          "SubjectName" : "MySQL",
...          "Marks" : 78
...       }
...    }
... );
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo639.insertOne(
... {
...    "_id" : 2,
...    "CountryName" : "UK",
...    "Info1" : {
...       "Name" : "Chris",
...       "SubjectName" : "MySQL",
...       "Marks" : 79
...    },
...    "Info2" : {
...          "Name" : "Chris",
...          "SubjectName" : "MySQL",
...          "Marks" : 88
...       }
...    }
... );
{ "acknowledged" : true, "insertedId" : 2 }

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

> db.demo639.find();

This will produce the following output −

{ "_id" : 1, "CountryName" : "US", "Info1" : { "Name" : "Chris", "SubjectName" : "MySQL", "Marks" : 78 }, "Info2" : { "Name" : "Chris", "SubjectName" : "MySQL", "Marks" : 78 } }
{ "_id" : 2, "CountryName" : "UK", "Info1" : { "Name" : "Chris", "SubjectName" : "MySQL", "Marks" : 79 }, "Info2" : { "Name" : "Chris", "SubjectName" : "MySQL", "Marks" : 88 } }

Following is the query for aggregation framework with $group query −

> db.demo639.aggregate({$group : {_id : {Name1:"$Info1.Name",Name2:"$Info2.Name"},
...
...    Marks:{$first:"$Info2.Marks"},
...    Marks:{$sum:"$Info2.Marks"}
... }}).pretty();

This will produce the following output −

{ "_id" : { "Name1" : "Chris", "Name2" : "Chris" }, "Marks" : 166 }
raja
Published on 12-May-2020 11:38:25
Advertisements