Merge two array fields in MongoDB?


To merge, use $setUnion operator. Let us first create a collection with documents −

> db.mergeTwoArrayFieldDemo.insertOne({"NaturalNumbers":[1,2,3,8,10,20,30],"WholeNumbers":[0,1,2,63,78,20,45]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd68e4057806ebf1256f11d")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.mergeTwoArrayFieldDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd68e4057806ebf1256f11d"),
   "NaturalNumbers" : [
      1,
      2,
      3,
      8,
      10,
      20,
      30
   ],
   "WholeNumbers" : [
      0,
      1,
      2,
      63,
      78,
      20,
      45
   ]
}

Following is the query to merge two array field in MongoDB.

> db.mergeTwoArrayFieldDemo.aggregate([
   { "$project": {
      "MergedArray": { "$setUnion": [ "$NaturalNumbers", "$WholeNumbers" ] }
   }}
]);

This will produce the following output −

{ "_id" : ObjectId("5cd68e4057806ebf1256f11d"), "MergedArray" : [ 0, 1, 2, 3, 8, 10, 20, 30, 45, 63, 78 ] }
raja
Published on 13-Jun-2019 11:20:01
Advertisements