Query a nested field within an array with MongoDB

To query a nested field within an array in MongoDB, use the $elemMatch operator to match documents where at least one array element satisfies all specified query criteria.

Syntax

db.collection.find({
    "arrayField": { 
        "$elemMatch": { 
            "nestedField": "value" 
        } 
    }
});

Sample Data

Let us create a collection with documents containing nested arrays ?

db.demo153.insertMany([
    {
        "ClientDetails": [
            {"ClientName": "Chris", "ClientProject": "Online Banking System"},
            {"ClientName": "David", "ClientProject": "Online School Management"}
        ]
    },
    {
        "ClientDetails": [
            {"ClientName": "Carol", "ClientProject": "Online Book System"},
            {"ClientName": "Mike", "ClientProject": "Game Development"}
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e351957fdf09dd6d08539df"),
        ObjectId("5e3519c9fdf09dd6d08539e0")
    ]
}

View All Documents

db.demo153.find();
{
    "_id": ObjectId("5e351957fdf09dd6d08539df"), 
    "ClientDetails": [
        { "ClientName": "Chris", "ClientProject": "Online Banking System" },
        { "ClientName": "David", "ClientProject": "Online School Management" }
    ]
}
{
    "_id": ObjectId("5e3519c9fdf09dd6d08539e0"), 
    "ClientDetails": [
        { "ClientName": "Carol", "ClientProject": "Online Book System" },
        { "ClientName": "Mike", "ClientProject": "Game Development" }
    ]
}

Example: Query Nested Field

Find documents where any client has the project "Online Banking System" ?

db.demo153.find({
    "ClientDetails": { 
        "$elemMatch": {
            "ClientProject": "Online Banking System"
        } 
    }
});
{
    "_id": ObjectId("5e351957fdf09dd6d08539df"), 
    "ClientDetails": [
        { "ClientName": "Chris", "ClientProject": "Online Banking System" },
        { "ClientName": "David", "ClientProject": "Online School Management" }
    ]
}

Key Points

  • $elemMatch matches documents where at least one array element meets all specified conditions.
  • Use $elemMatch for complex queries on array elements with multiple fields.
  • For simple field matching, dot notation can also work: {"ClientDetails.ClientProject": "value"}

Conclusion

The $elemMatch operator enables precise querying of nested fields within arrays, ensuring that all conditions are met within a single array element rather than across multiple elements.

Updated on: 2026-03-15T02:23:44+05:30

370 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements