MongoDB Operators

Beginner
10 min read
Updated: Oct 2026
Entry guide
Live examples

What Are MongoDB Operators?

MongoDB operators are special keys that start with $. They tell MongoDB how to work with your data—not just which field to look at.

You use operators to query, update, aggregate, transform, compare, and manipulate documents. Without them, you could only match exact field values; with them, you can express ranges, logic, math, arrays, and pipeline stages.

Remember
Operator = instruction that starts with $

Examples:
  $gt     → greater than (query / expression)
  $set    → set a field value (update / stage)
  $match  → filter documents in a pipeline
  $sum    → total values in a $group

Browse every tutorial in the left sidebar.

How MongoDB Operators Work

An operator is a named action. You place it where MongoDB expects an expression, filter, update, or stage. MongoDB reads the $name, applies the rule, and returns or modifies documents accordingly.

  1. Pick the context (query, update, or aggregation).
  2. Choose an operator that matches your goal (compare, set, filter, sum…).
  3. Pass field paths, literals, or nested expressions as arguments.
  4. Run the command; only matching or transformed documents are affected.
Where operators appearTypical use
Query filtersfind({ age: { $gt: 18 } })
Update operationsupdateOne({}, { $set: { active: true } })
Aggregation pipelinesaggregate([{ $match: … }, { $group: … }])
ExpressionsInside $project / $addFields
Array / document work$push, $pull, $filter, $map
mongosh
// Query filter
db.students.find({ score: { $gte: 80 } })

// Update
db.students.updateOne(
  { name: "Asha" },
  { $set: { grade: "A" } }
)

// Aggregation expression
db.students.aggregate([
  { $project: { total: { $add: ["$math", "$science"] } } }
])

How It Works

  1. Query: $gte keeps documents where score is at least 80.
  2. Update: $set writes grade: "A" on the matching student.
  3. Aggregation: $add computes a per-document total inside $project.

MongoDB Operator Syntax

Almost every operator uses the $operator form. The $ prefix marks a reserved name so MongoDB does not treat it as a normal field.

Pattern
{ $operatorName: <argument> }

// Field-path in aggregation (different meaning of $):
"$fieldName"   → value of that field on the current document

$gt

Match values greater than 100

{ price: { $gt: 100 } }

$set

Update (or pipeline stage) a field

{ $set: { status: "shipped" } }

$match

Filter documents in a pipeline

{ $match: { city: "Chennai" } }

$sum

Add values inside $group

{ total: { $sum: "$amount" } }

Tip: $field as an operator means “run this action.” "$field" as a string path means “read this field.” Beginners often mix those two meanings—keep them separate.

Pseudocode

Use this mental model before you type mongosh syntax.

Pseudocode
goal = what you need (filter / change / transform / total)

if goal is "find matching docs":
    use query operators ($gt, $in, $and, ...)
else if goal is "change stored fields":
    use update operators ($set, $unset, $push, ...)
else if goal is "pipeline analytics":
    use stages ($match, $group, ...)
    and expression / accumulator operators inside them

for each document:
    apply the operator rule
    keep, change, or emit the result

How It Works

  1. Start from the goal, not from a random operator name.
  2. Pick the family that matches that goal (query, update, or aggregation).
  3. Apply the operator to each document (or each group) and collect results.

Operator Categories

Major families below. The left sidebar lists individual tutorials—this section only explains when each family is useful.

CategoryUsed forExamples
Query & comparisonMatch documents by value relationships$eq, $gt, $in
LogicalCombine or negate conditions$and, $or, $not
ElementCheck field presence or BSON type$exists, $type
EvaluationExpressions, regex, JavaScript, schema$expr, $regex, $jsonSchema
ArrayRead or reshape arrays in expressions$filter, $size, $arrayElemAt
UpdateChange document fields in place$set, $unset, $inc
Field updateTargeted field writes during updates$set, $unset, $rename, $currentDate
Array updateModify array fields during updates$push, $pull, $addToSet, $pop
AggregationPipeline stages and per-document expressions$match, $add, $cond
BitwiseBit-level updates or matches on integers$bitsAllSet, $bit
GeospatialLocation queries and nearness$near, $geoWithin, $geoNear
MiscellaneousSpecial helpers and search aids$text, $comment, $meta

For rollups inside $group, see the accumulators hub. For pipeline steps, see aggregation stages.

Common MongoDB Operators

A short starter set. Open any name for a full tutorial when a page exists; use the sidebar for the complete catalog.

OperatorQuick meaning
$eqEqual to a value
$gt / $gteGreater than / greater or equal
$lt / $lteLess than / less or equal
$inValue is in a list
$and / $orCombine conditions
$set / $unsetSet or remove fields (update / stage)
$push / $pullAdd to or remove from arrays
$match / $project / $groupCore aggregation stages
$sumSum values (or count with $sum: 1)

Worked Example

Small students collection. We filter high scores with $gte, then average them with $group and $avg.

Example 1 — Sample Data

Three students with a numeric score.

mongosh
db.students.insertMany([
  { _id: 1, name: "Asha",  score: 92 },
  { _id: 2, name: "Ben",   score: 74 },
  { _id: 3, name: "Chitra", score: 88 }
]);

How It Works

  1. Insert three documents into students.
  2. Each document has a name and a numeric score.
  3. We will filter and aggregate these rows next.

Example 2 — Filter Then Average

Keep scores of 80 or higher, then compute one average for that set.

mongosh
db.students.aggregate([
  { $match: { score: { $gte: 80 } } },
  {
    $group: {
      _id: null,
      avgHighScore: { $avg: "$score" },
      count: { $sum: 1 }
    }
  }
]);

How It Works

  1. Select the collection. The pipeline reads from students.
  2. $match + $gte. Keeps Asha (92) and Chitra (88); drops Ben (74).
  3. $group + $avg. Averages the remaining scores: (92 + 88) / 2 = 90.
  4. $sum: 1. Counts how many documents entered the group (2).

Choosing the Right Operator

Match the job to the family first; then pick a specific operator.

If you need to…Start with
Compare valuesComparison operators ($gt, $eq, $in)
Combine multiple conditionsLogical operators ($and, $or)
Modify stored fieldsUpdate operators ($set, $unset, $inc)
Transform data in a pipelineAggregation stages & expression operators
Work with arraysArray operators / array update operators
Total or average many documentsAccumulators inside $group

Edge Cases & Pitfalls

Common beginner traps when learning MongoDB operators.

context

Query vs aggregation expression

{ score: { $gt: 80 } } works in find() / $match. Aggregation expression form is { $gt: ["$score", 80] }, often inside $expr. Same name, different shapes.

wrong place

Wrong context for an operator

$acos belongs in expression stages, not as a plain find() filter. $set belongs in updates (or as a pipeline stage), not alone in a filter.

$

Two meanings of $

$gt is an operator. "$score" is a field path. Confusing them causes syntax errors or unexpected nulls.

null

Null and missing fields

Missing fields often behave like null. Queries such as { field: null } can match both null and missing. Use $exists when you need to distinguish them.

arrays

Array vs scalar

Comparing against an array can match if any element satisfies the condition. Know whether your field is a scalar or an array before writing the filter.

types

Type-sensitive comparisons

"10" (string) is not equal to 10 (number). Store and compare consistent BSON types, or convert with operators like $toInt.

scope

Not every operator works everywhere

Some operators are query-only, update-only, or aggregation-only. Always check the context on the individual operator page.

Performance Notes

IdeaPractical tip
Operators are not “slow by default”Cost comes from how much data you scan and how you shape the query
Indexes matterIndex fields you filter and sort on often ($match / find)
Filter earlyPut $match near the start of aggregations
Avoid full scansPrefer selective filters over reading every document when possible

Use explain() when a query feels slow. Prefer correct indexes and smaller working sets over micro-optimizing a single operator choice.

Key Takeaways

  • Operators are $-prefixed instructions for querying, updating, and aggregating.
  • Context first: query, update, and aggregation operators are not interchangeable.
  • Learn families, then open individual tutorials from the left sidebar.
  • Watch types and nulls—comparisons are type-sensitive; missing fields often act like null.

One line: MongoDB operators are the vocabulary of filters, updates, and pipelines—pick the right family, then the right $name.

Frequently Asked Questions

Operators are special keys that start with $ and tell MongoDB how to query, update, compare, transform, or aggregate data. Examples include $gt for greater-than filters, $set for updates, and $sum inside $group.
The leading $ marks a reserved operator name so MongoDB can tell operators apart from ordinary field names in documents and queries.
Query operators (like $gt, $in, $or) select which documents match. Update operators (like $set, $unset, $push, $pull) change fields in matching documents. They are used in different commands: find/findOne vs updateOne/updateMany.
Yes. Operator names must match exactly, including the $ prefix and camelCase spelling—for example $dateToString, not $datetostring or $DateToString.
Yes. You can nest and combine them—for example $and with several comparisons in a filter, or $match then $group with $sum in an aggregation pipeline.
Use the left sidebar on this section to open each operator tutorial under /mongodb/operators/<name>. This page is the overview; individual pages cover syntax, examples, and pitfalls in depth.
Often yes. Query operators appear in find() filters. Aggregation expression operators run inside stages like $project and $addFields. Some names overlap (for example $gt) but the syntax and context differ—especially with $expr.

Next: $abs

Start the operator tutorials with absolute value in aggregation expressions.

$abs tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful