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 $unwind flattens the outer Info1 array
  • Second $unwind flattens the nested Info2 array
  • $match filters 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.

Updated on: 2026-03-15T03:12:59+05:30

253 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements