MongoDB Query Operators: The Ones You Actually Use
Most day-to-day work in MongoDB needs only about a dozen query operators: the comparison operators ($eq, $ne, $gt, $gte, $lt, $lte), set membership ($in, $nin), existence and type checks ($exists, $type), $regex, the logical operators ($and, $or, $not, $nor), the array operators ($elemMatch, $all, $size) and $expr for comparing fields inside one document. The operators themselves are easy. The traps are in how they treat missing fields, null, arrays and types. This page covers the MongoDB query operators you will actually reach for, with the behavior that surprises people.
All examples use mongosh against a hypothetical orders collection.
Comparison operators
A bare field/value pair is an implicit $eq:
db.orders.find({ status: "shipped" })
db.orders.find({ status: { $eq: "shipped" } }) // identical
Range operators combine inside one object:
db.orders.find({ total: { $gte: 50, $lt: 200 } })
Two rules to remember:
- Never repeat a key in the same filter object.
{ total: { $gt: 50 }, total: { $lt: 200 } }is a JavaScript object with a duplicate key, so the second one silently wins. Put both operators in one sub-document, or use$and. - Comparisons are type-bracketed.
{ total: { $gt: 50 } }only matches values that are numbers. A document wheretotalis the string"80"is not returned, and no error is raised. This is the usual reason a range query “misses” documents after an import that stored numbers as strings. Check with{ total: { $type: "string" } }.
$ne deserves a warning: { status: { $ne: "cancelled" } } also matches documents where status does not exist at all. If you mean “has a status, and it is not cancelled”, write it explicitly:
db.orders.find({ status: { $exists: true, $ne: "cancelled" } })
$in and $nin
$in replaces a chain of $or conditions on one field:
db.orders.find({ status: { $in: ["pending", "processing"] } })
It works well with indexes and is easier to read than the $or equivalent. Keep the list reasonably small; very large $in arrays make query planning and parsing slower.
$nin has the same quirk as $ne: it matches documents where the field is missing.
db.orders.find({ status: { $nin: ["cancelled", "refunded"] } })
// also returns documents with no "status" field
When the field holds an array, $in matches if any element is in the list.
$exists vs null
Three different questions look similar, and each has a different answer:
// field is null OR the field does not exist
db.users.find({ deletedAt: null })
// field does not exist (but a stored null does not match)
db.users.find({ deletedAt: { $exists: false } })
// field exists and is explicitly null
db.users.find({ deletedAt: { $type: "null" } })
{ field: null } is the one that catches people: it matches both missing and null. If your application writes null in some code paths and omits the field in others, this query treats them the same, which is often what you want for “not set” checks. For “never written” versus “written as null”, use $exists or $type.
For a “has a value” filter, { deletedAt: { $ne: null } } matches documents where the field exists and is not null.
$regex, and why to anchor it
db.users.find({ email: { $regex: "^alice@", $options: "i" } })
db.users.find({ email: /^alice@/ }) // shell shorthand
Performance depends on the shape of the pattern:
- A case-sensitive pattern anchored at the start (
^prefix) can use an index on the field as a bounded range scan. - An unanchored pattern (
alice) or one with theioption cannot use the index bounds effectively. MongoDB may still scan the whole index instead of the collection, which is cheaper but still linear.
For case-insensitive matching on large collections, consider a collation with strength: 2 on the index and query, or store a normalized lowercase copy of the field. For free-text search, a text index or Atlas Search is a better fit than regex.
Remember to escape user input before building a pattern; a dot or a plus sign in a search term changes the meaning. Use explain() to confirm what the planner does; reading explain() output takes only a few minutes.
Logical operators
Multiple top-level fields are combined with an implicit AND:
db.orders.find({ status: "shipped", total: { $gt: 50 } })
Use $or when you need alternatives, and wrap in $and only when you need the same key twice or must combine several $or groups:
db.orders.find({
$and: [
{ $or: [{ status: "pending" }, { status: "processing" }] },
{ $or: [{ priority: "high" }, { total: { $gt: 500 } }] }
]
})
$not inverts an operator expression on a single field ({ total: { $not: { $gt: 100 } } }) and, like $ne, also matches missing fields. $nor fails the document if any listed condition is true.
For $or to use indexes efficiently, each branch generally needs its own supporting index.
Arrays: dot notation vs $elemMatch
Matching a scalar against an array field checks whether any element equals it:
db.orders.find({ tags: "gift" })
Things get subtle with arrays of sub-documents. Suppose each order has an items array like { sku: "A1", qty: 2 }. This query:
db.orders.find({ "items.sku": "A1", "items.qty": { $gt: 5 } })
matches an order where one item has sku: "A1" and a different item has qty > 5. Each condition can be satisfied by a different element. To require both on the same element, use $elemMatch:
db.orders.find({ items: { $elemMatch: { sku: "A1", qty: { $gt: 5 } } } })
Use dot notation when one condition is enough, and $elemMatch whenever you need two or more conditions to hold for the same array element.
Other array helpers:
$allrequires every listed value to be present:{ tags: { $all: ["gift", "express"] } }.$sizematches an exact array length only; it does not accept ranges. For “at least N elements”, test for the existence of an index:{ "items.2": { $exists: true } }means at least three items.
$expr: comparing fields within a document
Plain filters compare a field to a constant. To compare two fields of the same document, use $expr with aggregation expressions:
// documents where the amount paid is less than the amount due
db.invoices.find({ $expr: { $lt: ["$paid", "$due"] } })
Field references inside $expr need the $ prefix. $expr also lets you use aggregation operators such as $dateDiff or $strLenCP in a find. Be aware that index usage inside $expr is more limited than with ordinary query operators and varies by server version and operator, so check explain() before running it against a large collection.
Quick traps summary
| You write | What you may not expect |
|---|---|
{ a: null } |
Matches missing fields too |
{ a: { $ne: x } }, $nin, $not |
Match documents where a is missing |
{ a: { $gt: 5 } } |
Ignores values that are not numbers |
{ a: /abc/i } |
Cannot use index bounds well; slow on big collections |
{ "arr.x": 1, "arr.y": 2 } |
Conditions may match different elements |
{ a: {...}, a: {...} } |
Duplicate key: the last one wins |
{ arr: { $size: { $gt: 1 } } } |
Invalid; $size takes an exact number |
Typing filters outside the shell
Filters like the ones above are shell syntax. Drivers use their own language’s syntax, and types such as ObjectId and dates need to be constructed explicitly in each one. The same issue applies when you type a filter on a small screen: shell-style filters such as { status: "shipped", total: { $gt: 50 } } are exactly what Bussola accepts on iPhone, which is convenient for quick checks. If you are editing documents rather than just reading them, see how to update a document without overwriting someone else’s change.
Checklist before you run a filter on production
- Does the filter use
$ne,$ninor$not? Decide whether missing fields should match. - Are the stored types what you expect? Check one document with
$type. - Is a regex anchored and case-sensitive, or is there a better option?
- Do multiple conditions on an array of sub-documents need
$elemMatch? - Have you looked at
explain("executionStats")and comparedtotalDocsExaminedwithnReturned? - Is the user allowed to write? For ad-hoc exploration, a read-only user removes the risk entirely.
Bussola is a free MongoDB client for iPhone: query, edit and aggregate over a direct connection, with no backend.
Coming soon to the App Store