MongoDB query to match documents that contain an array field

To match documents that contain an array field, use the $elemMatch operator. This operator matches documents where at least one array element meets all specified criteria within a single element.

Syntax

db.collection.find({
    "arrayField": {
        "$elemMatch": {
            "field1": "value1",
            "field2": "value2"
        }
    }
});

Sample Data

Let us create a collection with documents ?

db.demo592.insertMany([
    {
        "id": 101,
        "details": [
            { "Name": "Chris", "Value": "200" },
            { "Name": "David", "Value": "800" }
        ]
    },
    {
        "id": 102,
        "details": [
            { "Name": "Chris", "Value": "500" },
            { "Name": "David", "Value": "900" }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e930d8ffd2d90c177b5bcd6"),
        ObjectId("5e930d90fd2d90c177b5bcd7")
    ]
}

Display All Documents

db.demo592.find();
{ "_id": ObjectId("5e930d8ffd2d90c177b5bcd6"), "id": 101, "details": [
    { "Name": "Chris", "Value": "200" },
    { "Name": "David", "Value": "800" }
] }
{ "_id": ObjectId("5e930d90fd2d90c177b5bcd7"), "id": 102, "details": [
    { "Name": "Chris", "Value": "500" },
    { "Name": "David", "Value": "900" }
] }

Example: Complex Array Matching

Find documents where both Chris has Value >= 500 AND David has Value >= 600 ?

db.demo592.find({
    "$and": [
        { "details": { "$elemMatch": { "Name": "Chris", "Value": { "$gte": "500" } } } },
        { "details": { "$elemMatch": { "Name": "David", "Value": { "$gte": "600" } } } }
    ]
});
{ "_id": ObjectId("5e930d90fd2d90c177b5bcd7"), "id": 102, "details": [
    { "Name": "Chris", "Value": "500" },
    { "Name": "David", "Value": "900" }
] }

Key Points

  • $elemMatch ensures all conditions are met within a single array element
  • Use $and to match multiple array elements with different criteria
  • Without $elemMatch, conditions might match across different array elements

Conclusion

The $elemMatch operator is essential for querying arrays in MongoDB. It ensures that all specified conditions are satisfied by the same array element, providing precise matching for complex array queries.

Updated on: 2026-03-15T03:46:20+05:30

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements