Skip to main content

What does $expr do? When is $expr needed instead of standard filters?

$expr lets you use expressions and operations between fields within a single document while filtering. This isn't possible with plain filters, they only compare a field against a fixed value, while $expr can compare field to field, and run operations like $gt, $add, $subtract, and more.

When $expr is needed, in plain terms

It's used when a condition can't be expressed through a plain filter. For example:

  • you need to compare one field against another
  • you need to apply a calculation right inside the filter (addition, subtraction, etc.)
  • you need to use aggregation operators inside the query

An example: comparing field to field

The task: find documents where spent > limit (a plain filter can't do this, it only compares against a fixed value)

js
db.users.find({ $expr: { $gt: ["$spent", "$limit"] } })

An example: comparing against a calculation

Find products whose price is higher than a discounted version (price * 0.9):

js
db.products.find({ $expr: { $gt: ["$price", { $multiply: ["$discountPrice", 1.1] }] } })

The summary for a junior developer:

FilterWhen to use it
A plain { field: value }simple comparisons against constants
$exprcomparing field to field or complex expressions

The takeaway: $expr is needed when the filtering logic depends on calculations or comparisons between fields of the same document.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.