How to append to array in MongoDB?


To append to array in MongoDB, use $concatArrays. Let us create a collection with documents −

> db.demo435.insertOne({"FirstName":["Chris"],"LastName":["Brown"]} );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7719b1bbc41e36cc3cae97")
}
> db.demo435.insertOne({"FirstName":["David"],"LastName":["Miller"]} );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7719bdbbc41e36cc3cae98")
}
> db.demo435.insertOne({"FirstName":["John"],"LastName":["Doe"]} );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7719c6bbc41e36cc3cae99")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e7719b1bbc41e36cc3cae97"),
   "FirstName" : [
      "Chris"
      ],
      "LastName" : [
         "Brown"
      ]
   }
   {
      "_id" : ObjectId("5e7719bdbbc41e36cc3cae98"),
      "FirstName" : [
         "David"
      ],
      "LastName" : [
         "Miller"
      ]
   }
   {
      "_id" : ObjectId("5e7719c6bbc41e36cc3cae99"),
      "FirstName" : [
         "John"
      ],
      "LastName" : [
         "Doe"
   ]
}

Following is the query to append to array in MongoDB −

> db.demo435.aggregate([ { $project: { FullName: { $concatArrays: [ "$FirstName", "$LastName" ] } } } ])

This will produce the following output −

{ "_id" : ObjectId("5e7719b1bbc41e36cc3cae97"), "FullName" : [ "Chris", "Brown" ] }
{ "_id" : ObjectId("5e7719bdbbc41e36cc3cae98"), "FullName" : [ "David", "Miller" ] }
{ "_id" : ObjectId("5e7719c6bbc41e36cc3cae99"), "FullName" : [ "John", "Doe" ] }

Updated on: 03-Apr-2020

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements