Query Operators
Filtering data precisely is essential to working with MongoDB. Query operators let you go far beyond simple equality matches — comparing values, combining conditions, checking field existence, and querying inside arrays.
1. Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
$eq | Equal to | { age: { $eq: 25 } } |
$ne | Not equal to | { status: { $ne: "inactive" } } |
$gt / $gte | Greater than / or equal | { price: { $gt: 500 } } |
$lt / $lte | Less than / or equal | { stock: { $lte: 10 } } |
$in | Matches any value in array | { city: { $in: ["Delhi", "Mumbai"] } } |
$nin | Matches none of the values | { city: { $nin: ["Pune"] } } |
2. Logical Operators
// AND (implicit)
db.products.find({ category: "Electronics", price: { $lt: 5000 } })
// Explicit $and
db.products.find({
$and: [ { price: { $gt: 100 } }, { price: { $lt: 1000 } } ]
})
// $or
db.products.find({
$or: [ { category: "Books" }, { category: "Stationery" } ]
})
// $nor
db.products.find({
$nor: [ { inStock: false }, { discontinued: true } ]
})
3. Element Operators
// Field must exist
db.users.find({ phone: { $exists: true } })
// Field type check
db.users.find({ age: { $type: "int" } })
4. Array Operators
| Operator | Purpose | Example |
|---|---|---|
$all | Array contains all specified values | { tags: { $all: ["node", "react"] } } |
$size | Array has exact length | { tags: { $size: 3 } } |
$elemMatch | At least one array element matches all conditions | { scores: { $elemMatch: { $gt: 80, $lt: 95 } } } |
db.orders.find({
items: { $elemMatch: { product: "Laptop", quantity: { $gte: 2 } } }
})
$elemMatch, MongoDB matches if any combination of array elements satisfies the conditions separately — not necessarily the same element. Use $elemMatch when conditions must apply to a single array item.
5. Combining Operators
db.products.find({
$and: [
{ category: { $in: ["Electronics", "Computers"] } },
{ price: { $gte: 1000, $lte: 50000 } },
{ $or: [ { brand: "Dell" }, { brand: "HP" } ] }
]
})
6. Query Operators Checklist
- ✅ Master comparison operators — $gt, $lt, $in, $ne
- ✅ Combine conditions with $and, $or, $nor
- ✅ Check field existence and type with $exists, $type
- ✅ Query arrays precisely with $elemMatch and $all
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.