How to get the matching document inside an array in MongoDB?

To get the matching document inside an array in MongoDB, use the $elemMatch operator. This operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

Syntax

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

Sample Data

db.getMatchingDocumentDemo.insertMany([
    {
        _id: 1,
        "UserDetails": [
            {
                "UserName": "John",
                "UserAge": 23
            }
        ]
    },
    {
        _id: 2,
        "UserDetails": [
            {
                "UserName": "Larry",
                "UserAge": 24
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": 1,
        "1": 2
    }
}

Display all documents to verify the data ?

db.getMatchingDocumentDemo.find().pretty();
{
    "_id": 1,
    "UserDetails": [
        {
            "UserName": "John",
            "UserAge": 23
        }
    ]
}
{
    "_id": 2,
    "UserDetails": [
        {
            "UserName": "Larry",
            "UserAge": 24
        }
    ]
}

Example: Find Document with Matching Array Element

Find documents where UserDetails array contains an element with UserAge equal to 24 ?

db.getMatchingDocumentDemo.find({
    UserDetails: {
        $elemMatch: {
            UserAge: 24
        }
    }
});
{
    "_id": 2,
    "UserDetails": [
        {
            "UserName": "Larry",
            "UserAge": 24
        }
    ]
}

Key Points

  • $elemMatch returns the entire document when at least one array element matches all criteria.
  • Use $elemMatch when you need to match multiple conditions within the same array element.
  • Without $elemMatch, MongoDB would match conditions across different array elements.

Conclusion

The $elemMatch operator effectively finds documents containing array elements that match specific criteria. It ensures all conditions are satisfied by the same array element, making it essential for precise array queries.

Updated on: 2026-03-15T01:31:11+05:30

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements