MongoDB Operators Cheat Sheet: Query, Update and Aggregation
Checked against MongoDB MongoDB 9.0 manual (current) on 28 November 2026. Each section links to the official docs it was checked against.
This sheet covers the MongoDB operators you type most often in mongosh or a driver: filters, projections, updates and a handful of aggregation stages. It follows the MongoDB 9.0 manual, which the docs list as current. There was no MongoDB server or mongosh available while writing it, so every row is checked against the manual only.
When to use what
Start with plain equality filters and only add operators when you need them. { status: "A" } is shorter and easier to index-check than { status: { $eq: "A" } }. For several conditions on the same array element, use $elemMatch; without it each condition can be satisfied by a different element, which is the classic wrong-results bug.
For updates, prefer the operator form ($set, $inc, $push) over replacing the whole document. Operators change only the fields you name, so two writers touching different fields don't overwrite each other. Use $addToSet instead of $push when the array is a set of tags or IDs.
Reach for the aggregation pipeline when you need grouping, joins or reshaping that find can't do. Put $match first so later stages see fewer documents, and give the foreignField of a $lookup an index. If you think in SQL, the SQL to MongoDB converter translates a query into the equivalent filter or pipeline, and the schema design patterns post explains when to embed instead of joining. The MongoDB MCP server lets an AI assistant run these queries against your own cluster.
The manual groups $exists and $type under data type operators; the labels below are for scanning.
{ qty: { $gt: 20 } }Greater than; $gte, $lt and $lte work the same way
{ qty: { $ne: 0 } }Not equal to the given value
{ status: { $in: ["A", "D"] } }Field equals any value in the list; $nin is the negation
{ $or: [ { qty: { $lt: 20 } }, { price: 10 } ] }At least one clause must match
{ $and: [ {...}, {...} ] }All clauses must match, written as an explicit list
{ price: { $not: { $gt: 1.99 } } }Invert one condition on a field
{ $nor: [ {...}, {...} ] }Match documents that fail every clause
{ email: { $exists: false } }Documents where the field is absent
{ zip: { $type: "string" } }Match by BSON type, handy when a field holds mixed types
{ name: { $regex: /^acme/i } }Match string values against a regular expression
{ $expr: { $gt: ["$spent", "$budget"] } }Compare two fields of the same document with aggregation expressions
{ tags: { $all: ["red", "blank"] } }Array contains every listed value, in any order
{ results: { $elemMatch: { $gte: 80, $lt: 85 } } }One array element must satisfy all the conditions together
{ tags: { $size: 3 } }Array has exactly this many elements
db.students.find({}, { name: 1, age: 1 })Return only these fields plus _id
db.students.find({}, { name: 1, _id: 0 })Include fields and drop _id, the one allowed mix
db.students.find({}, { scores: 0, address: 0 })Return everything except these fields
{ name: 1, "address.city": 1 }Project an embedded field with dot notation
{ tags: { $slice: [1, 2] } }Skip one array element and return the next two
{ grades: { $elemMatch: { score: { $gt: 80 } } } }Return only the first array element that matches
Behaviour of $inc on missing or null fields is from https://www.mongodb.com/docs/manual/reference/operator/update/inc/; $unset details are from https://www.mongodb.com/docs/manual/reference/operator/update/unset/.
{ $set: { status: "active" } }Set a field's value; the updateOne examples show it adding a field that wasn't there
{ $unset: { label: "" } }Remove a field; the value you pass is ignored, and a missing field is left alone
{ $inc: { quantity: -2, "metrics.orders": 1 } }Add or subtract; a missing field is created with that value, a null field is an error
{ $push: { tags: "new" } }Append one item to an array
{ $push: { tags: { $each: ["a", "b"], $slice: -5 } } }Append several items and keep only the last five
{ $addToSet: { tags: "red" } }Append only if the value isn't already in the array
{ $pull: { votes: { $gte: 6 } } }Remove every array element that matches a condition
{ $pop: { scores: -1 } }Remove the first array element; 1 removes the last
{ $setOnInsert: { createdAt: new Date() } }Write a field only when an upsert inserts a new document
{ $rename: { nmae: "name" } }Rename a field in place
arrayFilters and upsert behaviour are from https://www.mongodb.com/docs/manual/reference/method/db.collection.updateOne/.
updateOne({ _id: 1, grades: 80 }, { $set: { "grades.$": 82 } })Update the first array element the filter matched; the array must be in the filter
{ $set: { "grades.$.std": 6 } }Update a field inside the first matching embedded document
{ $inc: { "grades.$[]": 10 } }Update every element of the array
updateOne(f, { $set: { "grades.$[el]": 100 } }, { arrayFilters: [ { el: { $gte: 100 } } ] })Update only the elements that match a named filter
updateOne(filter, update, { upsert: true })Insert a document built from the filter's equality fields and the update when nothing matches
$lookup syntax is from https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/.
{ $match: { year: { $lt: 1910 } } }Filter documents with query syntax; put it first
{ $group: { _id: "$year", titles: { $push: "$title" } } }One output document per distinct key, collecting values
{ $group: { _id: null, total: { $sum: "$runtime" }, n: { $sum: 1 } } }Totals and a count across the whole input
{ $project: { name: 1, _id: 0 } }Shape the output fields, same include/exclude rules as find
{ $lookup: { from: "comments", localField: "_id", foreignField: "movie_id", as: "comments" } }Left outer join; unmatched documents get an empty array
{ $sort: { _id: 1 } }Order documents; 1 ascending, -1 descending
{ $limit: 10 }Pass only the first n documents to the next stage
Worked example: Count page views with an upsert, then read the top pages
You want one counter document per page, created on the first view. An upsert with $inc and $setOnInsert does both jobs in one call:
db.pageviews.updateOne(
{ path: "/pricing" },
{
$inc: { views: 1 },
$setOnInsert: { firstSeen: new Date() }
},
{ upsert: true }
)
db.pageviews.aggregate([
{ $match: { views: { $gte: 100 } } },
{ $sort: { views: -1 } },
{ $limit: 5 },
{ $project: { _id: 0, path: 1, views: 1 } }
])
This wasn't run for this sheet, so here is what to look for. On the first call the result should show matchedCount: 0 and an upsertedId, and the new document gets path from the filter, views: 1 because $inc creates a missing field with the increment, and firstSeen. Later calls should show matchedCount: 1 and leave firstSeen untouched. Create a unique index on path first; the updateOne page says a uniquely indexed filter field is how you avoid multiple upserts. The pipeline then returns at most five documents holding only path and views.
Common mistakes
Writing
{ "grades.score": { $gte: 80 }, "grades.type": "exam" }and expecting one element to match both.Wrap the conditions in
$elemMatchso the same array element has to satisfy all of them.Passing a plain object as the update, such as
{ status: "done" }, toreplaceOnestyle code when you meant to change one field.Use
{ $set: { status: "done" } }withupdateOneso the other fields stay in place.Mixing inclusion and exclusion in a projection like
{ name: 1, age: 0 }.Pick one style;
_id: 0is the only exclusion allowed next to included fields.Using the positional
$withupsert: true.The positional operator needs an existing matched element, so drop the upsert or use
$pushorarrayFiltersinstead.Running
$incon a field that sometimes holdsnull.Clean those documents up first or set a numeric default, because
$incon a null value throws.Adding
$lookupwithout an index on the joined collection'sforeignField.Create that index; the manual says single equality joins perform poorly without it.
Related cheat sheets
Sources
- https://www.mongodb.com/docs/manual/reference/mql/query-predicates/
- https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results/
- https://www.mongodb.com/docs/manual/reference/operator/update/
- https://www.mongodb.com/docs/manual/reference/operator/update/inc/
- https://www.mongodb.com/docs/manual/reference/operator/update/unset/
- https://www.mongodb.com/docs/manual/reference/operator/update/positional/
- https://www.mongodb.com/docs/manual/reference/method/db.collection.updateOne/
- https://www.mongodb.com/docs/manual/reference/operator/aggregation/group/
- https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/
How we research: where our facts come from, how often we re-check them, and why no one can pay for a review or a verdict.