MongoDB Query Operators
Query operators like $eq, $gt, $lt, $in, $and, and $or extend simple equality filters into comparisons, ranges, membership tests, and logical combinations.
Why Query Operators Exist
A bare filter like { price: 20 } only ever expresses equality. The moment you need 'greater than', 'one of these values', or 'this OR that', you need a query operator. Operators are written as keys prefixed with a dollar sign inside the filter document, and MongoDB evaluates them as part of matching a document against the filter.
Comparison Operators
$eq, $ne, $gt, $gte, $lt, and $lte cover equality and range comparisons. { field: { $gt: value } } reads naturally as 'field is greater than value'. These are the operators you'll reach for constantly — filtering by price ranges, dates after a cutoff, or ratings above a threshold.
Range filters with comparison operators
// Price strictly greater than 50
db.products.find({ price: { $gt: 50 } })
// Price between 10 and 100, inclusive
db.products.find({
price: { $gte: 10, $lte: 100 }
})Membership with $in and $nin
$in matches a field against a list of acceptable values, replacing what would otherwise require several $or clauses. $nin is its inverse, matching documents whose field value is not present in the given list. Both are far more readable than chaining equality checks together with $or.
Match against a list of allowed values
// Status is one of these three values
db.orders.find({
status: { $in: ['pending', 'processing', 'shipped'] }
})
// Category is anything except these two
db.products.find({
category: { $nin: ['discontinued', 'archived'] }
})Combining Conditions with $and and $or
Multiple fields in the same filter object are already an implicit $and, so the explicit $and operator is mainly needed when you must apply more than one condition to the same field. $or, on the other hand, is used constantly: it takes an array of filter documents and matches any document satisfying at least one of them.
- Implicit AND — separate fields in one object are ANDed automatically
- $and — needed when combining multiple conditions on the same field
- $or — matches if any one of several filter documents is true
- $or and $and both take an array of filter documents as their value
Explicit $and and $or in practice
// price is either above 100 or the item is on sale
db.products.find({
$or: [
{ price: { $gt: 100 } },
{ onSale: true }
]
})
// price must satisfy two separate conditions on the same field
db.products.find({
$and: [
{ price: { $gt: 10 } },
{ price: { $lt: 20 } }
]
})Exercise: MongoDB Query Operators
What does the filter { age: { $gt: 30 } } match?