MongoDB query to unwind two arrays

To unwind two arrays in MongoDB, use multiple $unwind stages in an aggregation pipeline. This deconstructs each array field to create separate documents for every combination of array elements.

Syntax

db.collection.aggregate([
    { "$unwind": "$arrayField1" },
    { "$unwind": "$arrayField2" },
    { "$match": { /* optional filtering */ } }
])

Sample Data

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")
}

Example: Unwind Two Arrays with Matching

Unwind both arrays and match documents where Details1.Value equals Details.Value ?

db.demo387.aggregate([
    { "$unwind": "$Details1" },
    { "$unwind": "$Details" },
    { "$match": { "$expr":
        { "$eq": ["$Details1.Value", "$Details.Value"] }
    }}
])
{ "_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 } }

How It Works

  • First $unwind creates 3 documents (one for each Details1 element)
  • Second $unwind creates 9 total documents (3×3 combinations)
  • $match filters to keep only documents where Value fields match
  • Result: 3 documents with matching Value pairs

Conclusion

Use sequential $unwind stages to deconstruct multiple arrays, creating documents for each element combination. Add $match stages to filter the unwound results based on your criteria.

Updated on: 2026-03-15T02:46:20+05:30

749 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements