Tutorialspoint

Implement MongoDB $concatArrays even when some of the values are null?


1 Answer
Nishtha Thakur

Use aggregate framework along with $ifNull operator for this. The $concatArrays in aggregation is used to concatenate arrays. Let us first create a collection with documents −

>db.concatenateArraysDemo.insertOne({"FirstSemesterSubjects": ["MongoDB","MySQL","Java"],"SecondSemesterSubjects":["C","C++",]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd687707924bb85b3f4895c")
}
> db.concatenateArraysDemo.insertOne({"FirstSemesterSubjects":["C#","Ruby","Python"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd687927924bb85b3f4895d")
}
>db.concatenateArraysDemo.insertOne({"FirstSemesterSubjects":["HTML","CSS","Javascript"],"SecondSemesterSubjects":["CSS","Javascript"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd687bb7924bb85b3f4895e")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd687707924bb85b3f4895c"),
   "FirstSemesterSubjects" : [
      "MongoDB",
      "MySQL",
      "Java"
   ],
   "SecondSemesterSubjects" : [
      "C",
      "C++"
   ]
}
{
   "_id" : ObjectId("5cd687927924bb85b3f4895d"),
   "FirstSemesterSubjects" : [
      "C#",
      "Ruby",
      "Python"
   ]
}
{
   "_id" : ObjectId("5cd687bb7924bb85b3f4895e"),
   "FirstSemesterSubjects" : [
      "HTML",
      "CSS",
      "Javascript"
   ],
   "SecondSemesterSubjects" : [
      "CSS",
      "Javascript"
   ]
}

Following is the query to concatenate arrays even when null −

> db.concatenateArraysDemo.aggregate([
   {$project: {
      ConcatenateArrays: { '$concatArrays': [
         {$ifNull: ['$FirstSemesterSubjects', []]},
         {$ifNull: ['$SecondSemesterSubjects', []]}
      ] }
   } }
]);

This will produce the following output −

{ "_id" : ObjectId("5cd687707924bb85b3f4895c"), "ConcatenateArrays" : [ "MongoDB", "MySQL", "Java", "C", "C++" ] }
{ "_id" : ObjectId("5cd687927924bb85b3f4895d"), "ConcatenateArrays" : [ "C#", "Ruby", "Python" ] }
{ "_id" : ObjectId("5cd687bb7924bb85b3f4895e"), "ConcatenateArrays" : [ "HTML", "CSS", "Javascript", "CSS", "Javascript" ] }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.