Aggregate multiple arrays into one huge array with MongoDB?


To aggregate multiple arrays into a single array, use $project in MongoDB. Let us create a collection with documents −

> db.demo119.insertOne(
...    {
...       "_id": 101,
...       "WebDetails": [
...          {
...             "ImagePath": "/all/image1",
...             "isCorrect": "false"
...          },
...          {
...             "ImagePath": "/all/image2",
...             "isCorrect": "true"
...          }
...       ],
...       "ClientDetails": [
...          {
...             "Name": "Chris",
...             "isCorrect": "false"
...          },
...          {
...             "Name": "David",
...             "isCorrect": "true"
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }

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

> db.demo119.find();

This will produce the following output −

{
   "_id" : 101, "WebDetails" : [
      { "ImagePath" : "/all/image1", "isCorrect" : "false" },
      { "ImagePath" : "/all/image2", "isCorrect" : "true" } ], "ClientDetails" : [
      { "Name" : "Chris", "isCorrect" : "false" }, { "Name" : "David", "isCorrect" : "true" }
   ] 
}

Following is the query to aggregate multiple arrays into a single array with MongoDB −

>
> db.demo119.aggregate([
...    { "$project": {
...       "AllDetails": {
...          "$filter": {
...             "input": {
...                "$setUnion": [
...                   { "$ifNull": [ "$WebDetails", [] ] },
...                   { "$ifNull": [ "$ClientDetails", [] ] }
...                ]
...             },
...             "as": "out",
...             "cond": { "$eq": [ "$$out.isCorrect", "false" ] }
...          }
...       }
...    }},
...    { "$match": { "AllDetails.0": { "$exists": true } } }
... ])

This will produce the following output −

{ "_id" : 101, "AllDetails" : [ { "ImagePath" : "/all/image1", "isCorrect" : "false" }, { "Name" : "Chris", "isCorrect" : "false" } ] }

Updated on: 30-Mar-2020

303 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements