Select documents grouped by field in MongoDB?

MongoDBDatabaseBig Data Analytics

To select documents grouped by field in MongoDB, use $group along with $project. Let us first create a collection with documents −

> db.demo540.insertOne({id:1,"Name":"Chris","CountryName":"US"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8ca368ef4dcbee04fbbc0e")
}
> db.demo540.insertOne({id:1,"Name":"Chris","CountryName":"UK"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8ca36bef4dcbee04fbbc0f")
}
> db.demo540.insertOne({id:1,"Name":"Chris","CountryName":"AUS"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8ca370ef4dcbee04fbbc10")
}

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

> db.demo540.find();

This will produce the following output −

{ "_id" : ObjectId("5e8ca368ef4dcbee04fbbc0e"), "id" : 1, "Name" : "Chris", "CountryName" :
"US" }
{ "_id" : ObjectId("5e8ca36bef4dcbee04fbbc0f"), "id" : 1, "Name" : "Chris", "CountryName" :
"UK" }
{ "_id" : ObjectId("5e8ca370ef4dcbee04fbbc10"), "id" : 1, "Name" : "Chris", "CountryName" :
"AUS" }

Following is the query to select documents grouped by field −

> var query= [
... {
...    "$group": {
...       "_id": {
...          "id": "$id",
...          "Name": "$Name"
...       },
...       "details": {
...          "$push": {
...
...             "CountryName": "$CountryName"
...
...          }
...       }
...    }
... },
... {
...    "$project": {
...       "_id": "$_id.id",
...          "Name": "$_id.Name",
...             "details": 1
...       }
...    }
... ];
> db.demo540.aggregate(q).pretty();

This will produce the following output −

{
   "details" : [
      {
         "Name" : "Chris",
         "CountryName" : "US"
      },
      {
         "Name" : "Chris",
         "CountryName" : "UK"
      },
      {
         "Name" : "Chris",
         "CountryName" : "AUS"
      }
   ],
   "_id" : 1,
   "Name" : "Chris"
}
raja
Published on 14-May-2020 06:45:44
Advertisements