How to filter documents based on an array in MongoDB?

To filter documents based on an array in MongoDB, use the $elemMatch operator. The $elemMatch operator matches documents that contain an array field with at least one element that satisfies all the specified query criteria.

Syntax

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

Sample Data

Let us create a collection with documents ?

db.demo453.insertMany([
    { _id: 101, details: [ { Name: "David", Marks: 60 }, { Name: "Mike", Marks: 55} ] },
    { _id: 102, details: [ { Name: "Bob", Marks: 80 }, { Name: "Sam", Marks: 78} ] },
    { _id: 103, details: [ { Name: "Carol", Marks: 67 }, { Name: "John", Marks: 79} ] }
]);
{
    "acknowledged": true,
    "insertedIds": [101, 102, 103]
}

Display all documents from the collection ?

db.demo453.find();
{ "_id": 101, "details": [ { "Name": "David", "Marks": 60 }, { "Name": "Mike", "Marks": 55 } ] }
{ "_id": 102, "details": [ { "Name": "Bob", "Marks": 80 }, { "Name": "Sam", "Marks": 78 } ] }
{ "_id": 103, "details": [ { "Name": "Carol", "Marks": 67 }, { "Name": "John", "Marks": 79 } ] }

Example: Filter Documents with Array Elements

Find documents where at least one element in the details array has Marks greater than or equal to 75 ?

db.demo453.find(
    { details: { $elemMatch: {Marks: { $gte: 75 } } } }
);
{ "_id": 102, "details": [ { "Name": "Bob", "Marks": 80 }, { "Name": "Sam", "Marks": 78 } ] }
{ "_id": 103, "details": [ { "Name": "Carol", "Marks": 67 }, { "Name": "John", "Marks": 79 } ] }

Key Points

  • $elemMatch ensures at least one array element matches all specified conditions.
  • Without $elemMatch, MongoDB would match documents where different array elements satisfy different parts of the query.
  • Use $elemMatch when querying arrays of embedded documents with multiple field conditions.

Conclusion

The $elemMatch operator is essential for filtering documents based on array content, ensuring that all query conditions are satisfied by the same array element, providing precise and reliable results.

Updated on: 2026-03-15T03:01:51+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements