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
Return specific MongoDB embedded document
To return a specific embedded document in MongoDB, use the $unwind operator twice to flatten nested arrays, followed by $match to filter the desired embedded document based on specific criteria.
Syntax
db.collection.aggregate([
{ "$unwind": "$arrayField1" },
{ "$unwind": "$arrayField1.arrayField2" },
{ "$match": { "arrayField1.arrayField2.field": "value" } }
]);
Sample Data
Let us create a collection with nested embedded documents ?
db.demo631.insertOne({
id: "101",
Info1: [
{
CountryName: "US",
Info2: [
{
Name: "Chris",
Age: 24
},
{
Name: "Bob",
Age: 22
}
]
}
]
});
WriteResult({ "nInserted" : 1 })
Display all documents from the collection ?
db.demo631.find();
{
"_id": ObjectId("5e9b0eb16c954c74be91e6bf"),
"id": "101",
"Info1": [
{
"CountryName": "US",
"Info2": [
{ "Name": "Chris", "Age": 24 },
{ "Name": "Bob", "Age": 22 }
]
}
]
}
Example: Return Specific Embedded Document
Query to return the embedded document where Age is 22 ?
db.demo631.aggregate([
{ "$unwind": "$Info1" },
{ "$unwind": "$Info1.Info2" },
{ "$match": { "Info1.Info2.Age": 22 } }
]);
{
"_id": ObjectId("5e9b0eb16c954c74be91e6bf"),
"id": "101",
"Info1": {
"CountryName": "US",
"Info2": { "Name": "Bob", "Age": 22 }
}
}
How It Works
- First
$unwindflattens the outerInfo1array - Second
$unwindflattens the nestedInfo2array -
$matchfilters documents matching the specified criteria
Conclusion
Use double $unwind operations followed by $match to extract specific embedded documents from nested arrays. This approach flattens the structure and allows precise filtering of deeply nested data.
Advertisements
