MongoDB aggregate to convert multiple documents into single document with an array?


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

> db.demo248.insertOne({"id":101,"Name":"Chris","Age":21,"CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b6651627c0c63e7dba6d")
}
> db.demo248.insertOne({"id":101,"Name":"Bob","Age":22,"CountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b6741627c0c63e7dba6e")
}
> db.demo248.insertOne({"id":102,"Name":"Mike","Age":20,"CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b6811627c0c63e7dba6f")
}

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

> db.demo248.find();

This will produce the following output −

{ "_id" : ObjectId("5e46b6651627c0c63e7dba6d"), "id" : 101, "Name" : "Chris", "Age" : 21, "CountryName" : "US" }
{ "_id" : ObjectId("5e46b6741627c0c63e7dba6e"), "id" : 101, "Name" : "Bob", "Age" : 22, "CountryName" : "UK" }
{ "_id" : ObjectId("5e46b6811627c0c63e7dba6f"), "id" : 102, "Name" : "Mike", "Age" : 20, "CountryName" : "AUS" }

Following is the query to convert multiple documents into single document with an array −

> db.demo248.aggregate([
...   {
...      $group : {
...         _id : "$id",
...         details : {
...            $push : {
...               id:"$id",
...               Name:"$Name",
...               Age:"$Age",
...               CountryName:"$CountryName"
...            }
...         }
...      }
...   }
...])

This will produce the following output −

{ "_id" : 102, "details" : [ { "id" : 102, "Name" : "Mike", "Age" : 20, "CountryName" : "AUS" } ] }
{ "_id" : 101, "details" : [ { "id" : 101, "Name" : "Chris", "Age" : 21, "CountryName" : "US" }, { "id" : 101, "Name" : "Bob", "Age" : 22, "CountryName" : "UK" } ] }

Updated on: 30-Mar-2020

787 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements