How to match multiple criteria inside an array with MongoDB?

To match multiple criteria inside an array in MongoDB, use the $elemMatch operator with either find() or aggregate(). The $elemMatch operator matches documents where at least one array element satisfies all the specified criteria.

Syntax

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

Sample Data

db.demo84.insertMany([
    {
        "EmployeeDetails": [
            {Name: 'John', Salary: 45000, isMarried: true},
            {Name: 'Chris', Salary: 50000, isMarried: false}
        ]
    },
    {
        "EmployeeDetails": [
            {Name: 'Sam', Salary: 56000, isMarried: false},
            {Name: 'Bob', Salary: 50000, isMarried: false}
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e2c0a3471bf0181ecc422a5"),
        ObjectId("5e2c0a4071bf0181ecc422a6")
    ]
}

Example: Match Employee with Multiple Criteria

Find documents where an employee is named "Chris" AND is not married ?

db.demo84.find({
    "EmployeeDetails": {
        "$elemMatch": {
            "Name": "Chris",
            "isMarried": false
        }
    }
});
{
    "_id": ObjectId("5e2c0a3471bf0181ecc422a5"),
    "EmployeeDetails": [
        {"Name": "John", "Salary": 45000, "isMarried": true},
        {"Name": "Chris", "Salary": 50000, "isMarried": false}
    ]
}

Using Aggregate with $match

db.demo84.aggregate([
    {
        "$match": {
            "EmployeeDetails": {
                "$elemMatch": {
                    "Name": "Chris",
                    "isMarried": false
                }
            }
        }
    }
]);
{
    "_id": ObjectId("5e2c0a3471bf0181ecc422a5"),
    "EmployeeDetails": [
        {"Name": "John", "Salary": 45000, "isMarried": true},
        {"Name": "Chris", "Salary": 50000, "isMarried": false}
    ]
}

Key Points

  • $elemMatch ensures ALL specified conditions are met within the SAME array element.
  • Without $elemMatch, MongoDB would match different conditions across different array elements.
  • Works with both find() and aggregation pipeline $match stage.

Conclusion

Use $elemMatch to match multiple criteria within the same array element. This operator ensures all conditions are satisfied by a single array element, not across different elements in the array.

Updated on: 2026-03-15T01:52:28+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements