Match MongoDB documents with field value greater than a specific number and fetch them?

To match MongoDB documents with field values greater than a specific number, use the $gt operator in your query. This operator filters documents where the specified field value exceeds the given threshold.

Syntax

db.collection.find({ "fieldName": { "$gt": value } });

// Using with aggregation pipeline
db.collection.aggregate([
    { $match: { "fieldName": { "$gt": value } } }
]);

Sample Data

db.demo730.insertMany([
    { "Name": "Chris", "Marks": 33 },
    { "Name": "David", "Marks": 89 },
    { "Name": "Chris", "Marks": 45 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5eac54cd56e85a39df5f6339"),
        ObjectId("5eac54cd56e85a39df5f633a"),
        ObjectId("5eac54ce56e85a39df5f633b")
    ]
}

Display all documents from the collection ?

db.demo730.find();
{ "_id": ObjectId("5eac54cd56e85a39df5f6339"), "Name": "Chris", "Marks": 33 }
{ "_id": ObjectId("5eac54cd56e85a39df5f633a"), "Name": "David", "Marks": 89 }
{ "_id": ObjectId("5eac54ce56e85a39df5f633b"), "Name": "Chris", "Marks": 45 }

Example: Find Documents with Marks Greater than 40

db.demo730.find({ "Marks": { "$gt": 40 } });
{ "_id": ObjectId("5eac54cd56e85a39df5f633a"), "Name": "David", "Marks": 89 }
{ "_id": ObjectId("5eac54ce56e85a39df5f633b"), "Name": "Chris", "Marks": 45 }

Example: Using $match in Aggregation Pipeline

Combine $match with other pipeline stages for complex filtering ?

db.demo730.aggregate([
    { $sort: { _id: -1 } },
    { $limit: 3 },
    { $match: { $or: [ 
        { "Name": "Chris", "Marks": { "$gt": 40 } }, 
        { "Name": "David" } 
    ]}}
]);
{ "_id": ObjectId("5eac54ce56e85a39df5f633b"), "Name": "Chris", "Marks": 45 }
{ "_id": ObjectId("5eac54cd56e85a39df5f633a"), "Name": "David", "Marks": 89 }

Key Points

  • $gt operator finds values strictly greater than the specified number
  • Use $gte for greater than or equal to comparisons
  • $match in aggregation pipelines enables complex filtering with multiple conditions

Conclusion

The $gt operator effectively filters MongoDB documents based on numeric comparisons. Combine it with aggregation pipelines for advanced querying and sorting requirements.

Updated on: 2026-03-15T03:52:26+05:30

555 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements