Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
$unwindcreates 3 documents (one for each Details1 element) - Second
$unwindcreates 9 total documents (3×3 combinations) -
$matchfilters 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.
Advertisements
