Skip to content

Menu

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

From the docs, not run by us
{ qty: { $ne: 0 } }

Not equal to the given value

From the docs, not run by us
{ status: { $in: ["A", "D"] } }

Field equals any value in the list; $nin is the negation

From the docs, not run by us
{ $or: [ { qty: { $lt: 20 } }, { price: 10 } ] }

At least one clause must match

From the docs, not run by us
{ $and: [ {...}, {...} ] }

All clauses must match, written as an explicit list

From the docs, not run by us
{ price: { $not: { $gt: 1.99 } } }

Invert one condition on a field

From the docs, not run by us
{ $nor: [ {...}, {...} ] }

Match documents that fail every clause

From the docs, not run by us
{ email: { $exists: false } }

Documents where the field is absent

From the docs, not run by us
{ zip: { $type: "string" } }

Match by BSON type, handy when a field holds mixed types

From the docs, not run by us
{ name: { $regex: /^acme/i } }

Match string values against a regular expression

From the docs, not run by us
{ $expr: { $gt: ["$spent", "$budget"] } }

Compare two fields of the same document with aggregation expressions

From the docs, not run by us
{ tags: { $all: ["red", "blank"] } }

Array contains every listed value, in any order

From the docs, not run by us
{ results: { $elemMatch: { $gte: 80, $lt: 85 } } }

One array element must satisfy all the conditions together

From the docs, not run by us
{ tags: { $size: 3 } }

Array has exactly this many elements

From the docs, not run by us
db.students.find({}, { name: 1, age: 1 })

Return only these fields plus _id

From the docs, not run by us
db.students.find({}, { name: 1, _id: 0 })

Include fields and drop _id, the one allowed mix

From the docs, not run by us
db.students.find({}, { scores: 0, address: 0 })

Return everything except these fields

From the docs, not run by us
{ name: 1, "address.city": 1 }

Project an embedded field with dot notation

From the docs, not run by us
{ tags: { $slice: [1, 2] } }

Skip one array element and return the next two

From the docs, not run by us
{ grades: { $elemMatch: { score: { $gt: 80 } } } }

Return only the first array element that matches

From the docs, not run by us

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

From the docs, not run by us
{ $unset: { label: "" } }

Remove a field; the value you pass is ignored, and a missing field is left alone

From the docs, not run by us
{ $inc: { quantity: -2, "metrics.orders": 1 } }

Add or subtract; a missing field is created with that value, a null field is an error

From the docs, not run by us
{ $push: { tags: "new" } }

Append one item to an array

From the docs, not run by us
{ $push: { tags: { $each: ["a", "b"], $slice: -5 } } }

Append several items and keep only the last five

From the docs, not run by us
{ $addToSet: { tags: "red" } }

Append only if the value isn't already in the array

From the docs, not run by us
{ $pull: { votes: { $gte: 6 } } }

Remove every array element that matches a condition

From the docs, not run by us
{ $pop: { scores: -1 } }

Remove the first array element; 1 removes the last

From the docs, not run by us
{ $setOnInsert: { createdAt: new Date() } }

Write a field only when an upsert inserts a new document

From the docs, not run by us
{ $rename: { nmae: "name" } }

Rename a field in place

From the docs, not run by us

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

From the docs, not run by us
{ $set: { "grades.$.std": 6 } }

Update a field inside the first matching embedded document

From the docs, not run by us
{ $inc: { "grades.$[]": 10 } }

Update every element of the array

From the docs, not run by us
updateOne(f, { $set: { "grades.$[el]": 100 } }, { arrayFilters: [ { el: { $gte: 100 } } ] })

Update only the elements that match a named filter

From the docs, not run by us
updateOne(filter, update, { upsert: true })

Insert a document built from the filter's equality fields and the update when nothing matches

From the docs, not run by us

$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

From the docs, not run by us
{ $group: { _id: "$year", titles: { $push: "$title" } } }

One output document per distinct key, collecting values

From the docs, not run by us
{ $group: { _id: null, total: { $sum: "$runtime" }, n: { $sum: 1 } } }

Totals and a count across the whole input

From the docs, not run by us
{ $project: { name: 1, _id: 0 } }

Shape the output fields, same include/exclude rules as find

From the docs, not run by us
{ $lookup: { from: "comments", localField: "_id", foreignField: "movie_id", as: "comments" } }

Left outer join; unmatched documents get an empty array

From the docs, not run by us
{ $sort: { _id: 1 } }

Order documents; 1 ascending, -1 descending

From the docs, not run by us
{ $limit: 10 }

Pass only the first n documents to the next stage

From the docs, not run by us

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 $elemMatch so the same array element has to satisfy all of them.

  • Passing a plain object as the update, such as { status: "done" }, to replaceOne style code when you meant to change one field.

    Use { $set: { status: "done" } } with updateOne so the other fields stay in place.

  • Mixing inclusion and exclusion in a projection like { name: 1, age: 0 }.

    Pick one style; _id: 0 is the only exclusion allowed next to included fields.

  • Using the positional $ with upsert: true.

    The positional operator needs an existing matched element, so drop the upsert or use $push or arrayFilters instead.

  • Running $inc on a field that sometimes holds null.

    Clean those documents up first or set a numeric default, because $inc on a null value throws.

  • Adding $lookup without an index on the joined collection's foreignField.

    Create that index; the manual says single equality joins perform poorly without it.