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 wherefieldis greater thanvalue.{ field: { $gte: value } }finds documents wherefieldis greater than or equal tovalue.
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 >= 100Output
[
{ "_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
$gtwhen you mean to include the boundary value; use$gteinstead. - 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
| Operator | Meaning | Example |
|---|---|---|
| $gt | Greater than | { price: { $gt: 50 } } |
| $gte | Greater 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.