MongoDB query to unwind two arrays


To unwind, means to deconstruct an array field from the input documents to output a document for each element.

To unwind arrays, use $unwind in MongoDB aggregation. Let us first create a collection with documents −

> db.demo387.insertOne(
...    {
...
...       "Name" : "101",
...       "Details1" : [
...          {Value:100, Value1:50, Value2:40},
...          {Value:200},
...          {Value:300}
...       ],
...       "Details" : [
...          {Value:100, Value1:30, Value2:26},
...          {Value:200},
...          {Value:300}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5d197022064be7ab44e7f8")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e5d197022064be7ab44e7f8"),
   "Name" : "101",
   "Details1" : [
      {
         "Value" : 100,
         "Value1" : 50,
         "Value2" : 40
      },
      {
         "Value" : 200
      },
      {
         "Value" : 300
      }
   ],
   "Details" : [
      {
         "Value" : 100,
         "Value1" : 30,
         "Value2" : 26
      },
      {
         "Value" : 200
      },
      {
         "Value" : 300
      }
   ]
}

Following is the query to aggregate document with more than 1 array −

> db.demo387.aggregate([
...    { "$unwind": "$Details1" },
...    { "$unwind": "$Details" },
...    { "$match": { "$expr":
...    { "$eq": ["$Details1.Value", "$Details.Value"] }
... }}
... ])

This will produce the following output −

{ "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 100, "Value1" : 50, "Value2" : 40 }, "Details" : { "Value" : 100, "Value1" : 30, "Value2" : 26 } }
{ "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 200 }, "Details" : { "Value" : 200 } }
{ "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 300 }, "Details" : { "Value" : 300 } }

Updated on: 02-Apr-2020

429 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements