Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท CRUD and Queries

Mongoose Query Operators and Query Chaining

Filter with MongoDB operators in Mongoose ($gt, $in, $or, $regex, $exists) and build queries with the chainable where, sort, limit, skip and populate API.

Equality filters are only the start. Real applications need ranges, lists, alternatives and pattern matches. MongoDB expresses these with query operators, written as keys that begin with $. Mongoose passes them through to the database (after casting values), and it also offers a chainable query builder that is easier to read for complex queries. This lesson covers both.

Comparison operators

Operator Meaning Example
$eq equal { price: { $eq: 10 } } (same as { price: 10 })
$ne not equal { status: { $ne: 'archived' } }
$gt, $gte greater than, or equal { price: { $gt: 100 } }
$lt, $lte less than, or equal { price: { $lte: 20 } }
$in equals any value in a list { category: { $in: ['a', 'b'] } }
$nin equals none in the list { category: { $nin: ['c'] } }

Several operators on one field combine as an AND, which gives you ranges:

JavaScript
await Product.find({ price: { $gte: 10, $lt: 50 } });

Logical operators

JavaScript
await Product.find({ $or: [{ category: 'displays' }, { price: { $lt: 20 } }] });
await Product.find({ $and: [{ price: { $gt: 10 } }, { price: { $lt: 100 } }] });
await Product.find({ price: { $not: { $gt: 100 } } });
await Product.find({ $nor: [{ inStock: false }, { price: { $gt: 500 } }] });

Top-level keys in one filter object are ANDed already, so $and is needed only when you must repeat the same key.

Element and evaluation operators

JavaScript
await Product.find({ discount: { $exists: true } });     // field is present
await Product.find({ name: { $regex: /^mon/i } });       // pattern match
await Product.find({ name: /^mon/i });                   // shorthand for a regex
await Product.find({ tags: { $size: 3 } });              // array has exactly 3 items
await Product.find({ $expr: { $gt: ['$price', '$cost'] } }); // compare two fields

Regular expressions are powerful but a prefix-anchored pattern (/^mon/) can use an index, while a pattern such as /mon/ scans every value. If you put user input into a regex, escape it first; otherwise characters like . and * change the meaning and a crafted pattern can be slow.

Array operators

For a field that holds an array (tags: ['office', 'usb']):

JavaScript
await Product.find({ tags: 'usb' });                   // array contains 'usb'
await Product.find({ tags: { $all: ['usb', 'office'] } }); // contains both
await Product.find({ tags: { $in: ['usb', 'wifi'] } });    // contains either
await Product.find({ comments: { $elemMatch: { author: 'Bob', likes: { $gt: 2 } } } });

$elemMatch matters when you need several conditions to hold for the same array element.

The query builder

Every query method has a chainable equivalent. These two are the same:

JavaScript
await Product.find({ category: 'peripherals', price: { $lt: 50 } }).sort({ price: 1 }).limit(5);

await Product.find()
  .where('category').equals('peripherals')
  .where('price').lt(50)
  .sort({ price: 1 })
  .limit(5);

Common chain methods:

Method Purpose
where(path) then equals, gt, gte, lt, lte, in, nin, regex build conditions
or([...]), and([...]) logical operators
select(fields) projection
sort(spec) ordering
limit(n), skip(n) paging
populate(path) replace references with documents
lean() return plain objects
exec() run and return a real promise

You can build a query conditionally, which is the main reason to like chaining:

JavaScript
function searchProducts({ category, maxPrice, text, sort = 'name' }) {
  const query = Product.find();
  if (category) query.where({ category });
  if (maxPrice !== undefined) query.where('price').lte(maxPrice);
  if (text) query.where({ name: new RegExp(escapeRegex(text), 'i') });
  return query.sort(sort).limit(20);
}

The function returns a query; the caller decides when to execute it. That is the laziness described in How Mongoose works.

A filter matcher you can run

To see what these operators mean without a database, the stand-in below evaluates a filter against in-memory objects. It supports the main comparison, logical and array operators. It is a teaching sketch, not the real MongoDB engine.

Node.js Evaluating operators (stand-in, not MongoDB)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Chaining as a pipeline

The next stand-in builds a small chainable query class with where, gt, lt, sort, limit and skip to make the "assemble first, run later" idea visible.

Node.js A chainable query builder (stand-in, not Mongoose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  • Putting two conditions on the same key as separate top-level properties (the second overwrites the first). Use one object: { price: { $gt: 1, $lt: 9 } }.
  • Using user input in $regex without escaping it.
  • Using operators from query strings blindly: a client can send ?price[$gt]=0 and inject operators (NoSQL injection). Validate the type, or set sanitizeFilter: true.
  • Expecting $or conditions to use one index; each branch needs its own index.
  • Confusing $in (value in list) with $all (array contains all values).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which filter returns products priced from 10 up to, but not including, 50?

    $gte includes 10 and $lt excludes 50. There is no $between operator.
  2. 2. What does { tags: { $all: ['usb', 'office'] } } match?

    $all requires every listed value to be present in the array.
  3. 3. Why is it risky to pass req.query straight into find()?

    Query string parsers can create nested objects like { price: { $gt: 0 } }, which become operators. Validate input or use sanitizeFilter.
  4. 4. What is the main benefit of the chainable query builder?

    A query is lazy, so you can add where, sort and limit calls conditionally and run it once.

Summary

  • Operators such as $gt, $in, $or, $regex, $exists, $all and $elemMatch express ranges, lists, alternatives and array conditions.
  • Several operators on one field form a range; top-level keys are ANDed.
  • The chainable API (where, sort, limit, select, populate, lean) builds the same filters step by step and runs on await or exec().
  • Escape regex input and never trust client-supplied operators.

Next: Updating documents