How to merge array of documents in Mongo DB?


To merge, use aggregate() along with $PUSH. Let us create a collection with documents −

> db.demo64.insertOne({"Subjects":["MySQL","MongoDB","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e28762bcfb11e5c34d89936")
}
> db.demo64.insertOne({"Subjects":["Oracle","Spring","Python"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e28763fcfb11e5c34d89937")
}

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

> db.demo64.find();

This will produce the following output −

{ "_id" : ObjectId("5e28762bcfb11e5c34d89936"), "Subjects" : [ "MySQL", "MongoDB", "Java" ] }
{ "_id" : ObjectId("5e28763fcfb11e5c34d89937"), "Subjects" : [ "Oracle", "Spring", "Python" ] }

Following is the query to merge array of document in MongoDB −

> db.demo64.aggregate([
... { "$group": {
...    "_id": null,
...    "Subjects": { "$push": "$Subjects" }
... }},
... { "$project": { "_id": 0 }}
... ]);

This will produce the following output −

{ "Subjects" : [ [ "MySQL", "MongoDB", "Java" ], [ "Oracle", "Spring", "Python" ] ] }

Updated on: 30-Mar-2020

712 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements