Perform MongoDB array concatenation to concatenate records


For array concatenation, use $concatArrays operator. Let us first create a collection with documents −

>db.arrayConcatenationDemo.insertOne({"TeacherName":["Chris","Robert"],"StudentName":["Mike","Sam"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce921c078f00858fb12e911")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5ce921c078f00858fb12e911"),
   "TeacherName" : [
      "Chris",
      "Robert"
   ],
   "StudentName" : [
      "Mike",
      "Sam"
   ]
}

Following is the query for array concatenation −

> db.arrayConcatenationDemo.aggregate([
   { "$project": {
      "StudentAndTeacherName": { "$concatArrays": [ "$TeacherName", "$StudentName" ] }
   }}
]);

This will produce the following output −

{ "_id" : ObjectId("5ce921c078f00858fb12e911"), "StudentAndTeacherName" : [ "Chris", "Robert", "Mike", "Sam" ] }

Updated on: 30-Jul-2019

69 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements