Filter by several array elements in MongoDB?

To filter documents by several array elements in MongoDB, use the $elemMatch operator. This operator matches documents containing an array field with at least one element that satisfies all specified query criteria.

Syntax

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

Sample Data

Let us create a collection with documents containing nested arrays ?

db.filterBySeveralElementsDemo.insertMany([
    {
        "_id": 100,
        "StudentDetails": [
            {
                "StudentName": "John",
                "StudentCountryName": "US"
            },
            {
                "StudentName": "Carol",
                "StudentCountryName": "UK"
            }
        ]
    },
    {
        "_id": 101,
        "StudentDetails": [
            {
                "StudentName": "Sam",
                "StudentCountryName": "AUS"
            },
            {
                "StudentName": "Chris",
                "StudentCountryName": "US"
            }
        ]
    }
]);
{ "acknowledged": true, "insertedIds": [100, 101] }

Display all documents to verify the data ?

db.filterBySeveralElementsDemo.find().pretty();
{
    "_id": 100,
    "StudentDetails": [
        {
            "StudentName": "John",
            "StudentCountryName": "US"
        },
        {
            "StudentName": "Carol",
            "StudentCountryName": "UK"
        }
    ]
}
{
    "_id": 101,
    "StudentDetails": [
        {
            "StudentName": "Sam",
            "StudentCountryName": "AUS"
        },
        {
            "StudentName": "Chris",
            "StudentCountryName": "US"
        }
    ]
}

Example: Filter by Multiple Array Element Fields

Find documents where StudentDetails array contains an element with both StudentName "Sam" AND StudentCountryName "AUS" ?

db.filterBySeveralElementsDemo.find({
    StudentDetails: {
        $elemMatch: {
            StudentName: "Sam",
            StudentCountryName: "AUS"
        }
    }
}).pretty();
{
    "_id": 101,
    "StudentDetails": [
        {
            "StudentName": "Sam",
            "StudentCountryName": "AUS"
        },
        {
            "StudentName": "Chris",
            "StudentCountryName": "US"
        }
    ]
}

Key Points

  • $elemMatch ensures all conditions match within the same array element
  • Returns the entire document when a match is found, not just the matching array element
  • Use when you need to match multiple fields within a single array object

Conclusion

The $elemMatch operator provides precise filtering for complex array structures by ensuring all specified conditions match within the same array element, making it essential for querying documents with nested object arrays.

Updated on: 2026-03-15T01:35:21+05:30

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements