Extract particular element in MongoDB within a Nested Array?

To extract particular elements in MongoDB within nested arrays, use the $elemMatch operator to match array elements and projection to return only specific fields from the matched documents.

Syntax

db.collection.find(
    {
        "arrayField": {
            $elemMatch: {
                "nestedArrayField": {
                    $elemMatch: { "field": "value" }
                }
            }
        }
    },
    { "projection.field": 1 }
);

Sample Data

db.particularElementDemo.insertOne({
    "GroupId": "Group-1",
    "UserDetails": [
        {
            "UserName": "John",
            "UserOtherDetails": [
                {
                    "UserEmailId": "John123@gmail.com",
                    "UserFriendName": [
                        {
                            "Name": "Chris"
                        }
                    ]
                },
                {
                    "UserEmailId": "John22@hotmail.com",
                    "UserFriendName": [
                        {
                            "Name": "Robert"
                        }
                    ]
                }
            ]
        }
    ]
});
{ "acknowledged": true, "insertedId": 100 }

Example: Extract Friend Name "Robert"

Find documents where a user has a friend named "Robert" and project only the friend names ?

db.particularElementDemo.find(
    {
        "UserDetails": {
            $elemMatch: {
                "UserOtherDetails": {
                    $elemMatch: {
                        "UserFriendName": { $elemMatch: { "Name": "Robert" } }
                    }
                }
            }
        }
    },
    { "UserDetails.UserOtherDetails.UserFriendName.Name": 1 }
);
{ 
    "_id": 100, 
    "UserDetails": [ 
        { 
            "UserOtherDetails": [ 
                { "UserFriendName": [ { "Name": "Chris" } ] }, 
                { "UserFriendName": [ { "Name": "Robert" } ] } 
            ] 
        } 
    ] 
}

Key Points

  • $elemMatch is used for each level of nested arrays to match specific elements.
  • Projection with dot notation extracts only the required fields from matched documents.
  • Multiple nested $elemMatch operators handle deeply nested array structures.

Conclusion

Use nested $elemMatch operators to query deeply nested arrays and projection to extract specific elements. This approach efficiently filters and returns only the relevant data from complex nested structures.

Updated on: 2026-03-15T01:36:29+05:30

684 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements