MongoDB query to group several fields using aggregation framework?

MongoDBDatabaseBig Data Analytics

To group several fields, use $group in MongoDB. Let us create a collection with documents −

> db.demo192.insertOne({"Name":"Chris","Age":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3adb9f03d395bdc21346cd")
}
> db.demo192.insertOne({"Name":"David","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3adba103d395bdc21346ce")
}
> db.demo192.insertOne({"Name":"Chris","Age":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3adba503d395bdc21346cf")
}
> db.demo192.insertOne({"Name":"Mike","Age":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3adbbf03d395bdc21346d0")
}

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

> db.demo192.find();

This will produce the following output −

{ "_id" : ObjectId("5e3adb9f03d395bdc21346cd"), "Name" : "Chris", "Age" : 22 }
{ "_id" : ObjectId("5e3adba103d395bdc21346ce"), "Name" : "David", "Age" : 21 }
{ "_id" : ObjectId("5e3adba503d395bdc21346cf"), "Name" : "Chris", "Age" : 22 }
{ "_id" : ObjectId("5e3adbbf03d395bdc21346d0"), "Name" : "Mike", "Age" : 24 }

Following is the query to group several fields using aggregation framework −

> db.demo192.aggregate([{$group:{_id:{Age:"$Age",Name:"$Name"}}}]);

This will produce the following output −

{ "_id" : { "Age" : 24, "Name" : "Mike" } }
{ "_id" : { "Age" : 21, "Name" : "David" } }
{ "_id" : { "Age" : 22, "Name" : "Chris" } }
raja
Published on 27-Mar-2020 12:59:43
Advertisements