MongoDB query to match documents with array values greater than a specific value

To match documents with array values greater than a specific value in MongoDB, use the $elemMatch operator. The $elemMatch 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: { $gt: value } } }
);

Create Sample Data

Let us create a collection with documents ?

db.demo701.insertMany([
    { "ListOfValues": [100, 200, 300] },
    { "ListOfValues": [500, 700, 1000] },
    { "ListOfValues": [300, 350, 450] }
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5ea6e8cf551299a9f98c93b0"),
        ObjectId("5ea6e8d8551299a9f98c93b1"),
        ObjectId("5ea6e8e1551299a9f98c93b2")
    ]
}

Display all documents from a collection with the help of find() method ?

db.demo701.find();
{ "_id" : ObjectId("5ea6e8cf551299a9f98c93b0"), "ListOfValues" : [ 100, 200, 300 ] }
{ "_id" : ObjectId("5ea6e8d8551299a9f98c93b1"), "ListOfValues" : [ 500, 700, 1000 ] }
{ "_id" : ObjectId("5ea6e8e1551299a9f98c93b2"), "ListOfValues" : [ 300, 350, 450 ] }

Example: Find Documents with Array Values Greater Than 500

Following is the query to match documents with array values greater than a specific value ?

db.demo701.find({
    "ListOfValues": { $elemMatch: { $gt: 500 } }
});
{ "_id" : ObjectId("5ea6e8d8551299a9f98c93b1"), "ListOfValues" : [ 500, 700, 1000 ] }

How It Works

The $elemMatch operator evaluates each array element against the condition { $gt: 500 }. If at least one element in the array satisfies the condition, the entire document is returned.

Conclusion

Use $elemMatch with comparison operators like $gt to find documents where array elements meet specific criteria. This operator ensures that at least one array element matches the specified condition.

Updated on: 2026-03-15T03:39:58+05:30

901 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements