0
0
MongodbHow-ToBeginner · 3 min read

How to Use $lt and $lte in MongoDB Queries

In MongoDB, use $lt to find documents where a field's value is less than a specified value, and $lte to find documents where the field's value is less than or equal to a specified value. These operators are used inside query objects to filter data based on numeric or date comparisons.
📐

Syntax

The $lt and $lte operators are used in MongoDB queries to compare field values.

  • $lt: Matches values less than the specified value.
  • $lte: Matches values less than or equal to the specified value.

They are used inside a query object with the field name as the key.

json
{
  "field": { "$lt": value }
}

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

Example

This example shows how to find products priced less than 50 and products priced less than or equal to 50 in a collection named products.

javascript
db.products.insertMany([
  { name: "Pen", price: 20 },
  { name: "Notebook", price: 50 },
  { name: "Backpack", price: 80 }
])

// Find products with price less than 50
const lessThan50 = db.products.find({ price: { $lt: 50 } }).toArray()

// Find products with price less than or equal to 50
const lessThanOrEqual50 = db.products.find({ price: { $lte: 50 } }).toArray()

print('Products with price < 50:', JSON.stringify(lessThan50))
print('Products with price <= 50:', JSON.stringify(lessThanOrEqual50))
Output
Products with price < 50: [{"_id":"...","name":"Pen","price":20}] Products with price <= 50: [{"_id":"...","name":"Pen","price":20},{"_id":"...","name":"Notebook","price":50}]
⚠️

Common Pitfalls

Common mistakes when using $lt and $lte include:

  • Using them outside of a field query object, which causes syntax errors.
  • Confusing $lt (less than) with $lte (less than or equal to).
  • Applying these operators on non-comparable data types like strings without understanding lexicographical order.
javascript
/* Wrong: Using $lt without field key */
db.products.find({ $lt: 50 })

/* Right: Use $lt inside field query */
db.products.find({ price: { $lt: 50 } })
📊

Quick Reference

OperatorMeaningExample
$ltLess than{ price: { $lt: 100 } }
$lteLess than or equal to{ price: { $lte: 100 } }

Key Takeaways

Use $lt to find documents where a field is less than a value.
Use $lte to find documents where a field is less than or equal to a value.
Always place $lt and $lte inside the field's query object.
Be careful not to confuse $lt (less than) with $lte (less than or equal).
These operators work well with numbers and dates but be cautious with strings.