MongoDB query for array concatenation?


To concatenate, use $concatArrays in MongoDB. Let us first create a collection with documents −

>db.demo14.insertOne({"ListOfStudent":["Carol","Mike","Sam"],"ListOfTeacher":["Robert","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e0f754bd7df943a7cec4faa")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e0f754bd7df943a7cec4faa"),
   "ListOfStudent" : [
      "Carol",
      "Mike",
      "Sam"
   ],
   "ListOfTeacher" : [
      "Robert",
      "David"
   ]
}

Following is the query to concatenate array −

> db.demo14.aggregate([
... { "$project": {
...    "ListOfPeople": { "$concatArrays": [ "$ListOfStudent", "$ListOfTeacher" ] }
... }}
... ]);

This will produce the following output −

{ "_id" : ObjectId("5e0f754bd7df943a7cec4faa"), "ListOfPeople" : [ "Carol", "Mike", "Sam", "Robert", "David" ] }

Updated on: 01-Apr-2020

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements