Unwind two arrays from MongoDB


To unwind, use $unwind. The $unwind deconstructs an array field from the input documents to output a document for each element.

Let us create a collection with documents −

> db.demo515.insertOne(
... {
...    "details1": [
...       "4700100004"
...    ],
...    "details2": [
...       "Not Given"
...    ],
...    "Value1": [
...       "56",
...       "45",
...       "35",
...    ],
...    "Value2": [
...       "35",
...       "45",
...       "56",
...    ]}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e889e51987b6e0e9d18f590")
}

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

> db.demo515.find();

This will produce the following output −

{ "_id" : ObjectId("5e889e51987b6e0e9d18f590"), "details1" : [ "4700100004" ], "details2" : [
"Not Given" ], "Value1" : [ "56", "45", "35" ], "Value2" : [ "35", "45", "56" ] }

Following is the query to unwind two arrays −

> db.demo515.aggregate([
... { $unwind: { path: "$Value1", includeArrayIndex : "index1" } },
... { $unwind: { path: "$Value2", includeArrayIndex : "index2" } },
... { $project: {
...    _id : 1,
...    details1: 1,
...    details2: 1,
...    Value1: 1,
...    Value2: 1,
...    valid: { $eq: ["$index1", "$index2"] } }
... },
... { $match: { valid: true } }
... ]);

This will produce the following output −

{ "_id" : ObjectId("5e889e51987b6e0e9d18f590"), "details1" : [ "4700100004" ], "details2" : [
"Not Given" ], "Value1" : "56", "Value2" : "35", "valid" : true }
{ "_id" : ObjectId("5e889e51987b6e0e9d18f590"), "details1" : [ "4700100004" ], "details2" : [
"Not Given" ], "Value1" : "45", "Value2" : "45", "valid" : true }
{ "_id" : ObjectId("5e889e51987b6e0e9d18f590"), "details1" : [ "4700100004" ], "details2" : [
"Not Given" ], "Value1" : "35", "Value2" : "56", "valid" : true }

Updated on: 13-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements