MongoDB $elemMatch to match document

The $elemMatch operator in MongoDB matches documents that contain an array field with at least one element matching all specified query criteria. It's particularly useful when working with arrays of embedded documents.

Syntax

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

Sample Data

Let us create a collection with documents −

db.demo313.insertMany([
    { "_id": 100, "details": [{ "Name": "Chris", "Age": 24 }] },
    { "_id": 101, "details": [{ "Name": "David", "Age": 22 }] },
    { "_id": 102, "details": [{ "Name": "Mike", "Age": 25 }] }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": 100,
        "1": 101,
        "2": 102
    }
}

Display all documents from the collection −

db.demo313.find();
{ "_id": 100, "details": [ { "Name": "Chris", "Age": 24 } ] }
{ "_id": 101, "details": [ { "Name": "David", "Age": 22 } ] }
{ "_id": 102, "details": [ { "Name": "Mike", "Age": 25 } ] }

Example: Using $elemMatch in Projection

Following is the query to match document with $elemMatch in MongoDB −

db.demo313.find(
    { _id: 101 },
    { details: { $elemMatch: { Age: 22 } } }
);
{ "_id": 101, "details": [ { "Name": "David", "Age": 22 } ] }

Key Points

  • $elemMatch can be used in both query and projection operations
  • In projection, it returns only the first matching array element
  • Useful for filtering specific elements from arrays of embedded documents

Conclusion

The $elemMatch operator provides precise control when querying arrays of embedded documents, allowing you to match multiple conditions within a single array element and project only matching elements.

Updated on: 2026-03-15T02:22:49+05:30

387 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements