0
0
MongodbHow-ToBeginner · 3 min read

How to Use $gt and $gte Operators in MongoDB Queries

In MongoDB, use the $gt operator to find documents where a field's value is greater than a specified value, and use $gte to find documents where the field's value is greater than or equal to that value. These operators are used inside query filters to compare numeric or date fields.
📐

Syntax

The $gt and $gte operators are used inside a query filter object to compare field values.

  • { field: { $gt: value } } finds documents where field is greater than value.
  • { field: { $gte: value } } finds documents where field is greater than or equal to value.
json
{
  "field": { "$gt": value }
}

{
  "field": { "$gte": value }
}
💻

Example

This example shows how to find products with a price greater than 100 using $gt, and products with a price greater than or equal to 100 using $gte.

mongodb
db.products.find({ price: { $gt: 100 } })

// Returns products with price > 100

db.products.find({ price: { $gte: 100 } })

// Returns products with price >= 100
Output
[ { "_id": 1, "name": "Laptop", "price": 150 }, { "_id": 2, "name": "Monitor", "price": 200 } ] [ { "_id": 1, "name": "Laptop", "price": 150 }, { "_id": 2, "name": "Monitor", "price": 200 }, { "_id": 3, "name": "Keyboard", "price": 100 } ]
⚠️

Common Pitfalls

Common mistakes include:

  • Using $gt when you mean to include the boundary value; use $gte instead.
  • Applying these operators to non-numeric or non-date fields without understanding the data type, which can cause unexpected results.
  • Forgetting to wrap the operator inside the field object in the query filter.
mongodb
/* Wrong: operator outside field */
db.products.find({ $gt: { price: 100 } })

/* Right: operator inside field */
db.products.find({ price: { $gt: 100 } })
📊

Quick Reference

OperatorMeaningExample
$gtGreater than{ price: { $gt: 50 } }
$gteGreater than or equal to{ price: { $gte: 50 } }

Key Takeaways

Use $gt to find values strictly greater than a specified value.
Use $gte to include values equal to or greater than the specified value.
Always place $gt and $gte inside the field object in the query filter.
Ensure the field data type supports comparison (numbers, dates).
Double-check your query logic to avoid excluding boundary values unintentionally.