Queries, indexes and aggregation

Query operators, compound and multikey indexes, ESR rule, and the aggregation pipeline with $lookup and $group.

11 min read🍃 MongoDB

A MongoDB query is a document that describes the documents you want. An index is a B-tree over the fields you filter and sort by, the same structure the SQL course's index lesson drew. The aggregation pipeline is where the joins, groups and reshaping happen. The operators are different from SQL, but the reasoning about what an index can and cannot do for a query is exactly the same, and explain is how you check rather than guess.

Query operators

plaintext
db.orders.find({ "customer.id": id, status: { $in: ["PAID", "SHIPPED"] }, placedAt: { $gte: since } })
         .sort({ placedAt: -1 }).limit(20)

Equality is a bare value. The comparisons are $in, $gt/$gte/$lt/$lte, $ne, $exists and $regex. $and is implicit between fields and explicit when you need the same field twice, and $or is a list of clauses.

Dot notation reaches into embedded documents and arrays: "lines.sku": "A-1" matches an order with any line for that SKU. $elemMatch is for when several conditions must hold on the same array element (lines: { $elemMatch: { sku: "A-1", qty: { $gt: 5 } } }). The plain form { "lines.sku": "A-1", "lines.qty": { $gt: 5 } } matches an order whose some line has the SKU and some other line has the quantity.

Projection ({ lines: 0 }, or { orderNumber: 1, status: 1 }) trims the document the same way a select list does, and for the same reason: the network and the driver pay for every field you did not need. In Spring Data, Query and Criteria build the same documents, and a derived repository method builds them for you.

Index types

A single-field index on placedAt serves a range and a sort. A compound index on { "customer.id": 1, placedAt: -1 } serves the query above entirely: equality on the first field, range and sort on the second, in the index's own order. A multikey index is what you get when an indexed field is an array — one index entry per element, so "lines.sku" indexes every SKU of every order, with the constraint that a compound index may contain at most one array field. A unique index enforces orderNumber; a partial index (partialFilterExpression: { status: "OPEN" }) indexes only the documents that match, which is the SQL course's partial index and the right answer for "open orders" when 99% are closed. A TTL index on a date field expires documents after N seconds, which is a session or a token store with no cleanup job. A text index does basic full-text search and is the point at which the search course starts making the case for Elasticsearch. And _id is always indexed and always unique.

Every index costs what it costs in SQL:

  • write amplification on every insert and update of an indexed field;
  • memory (the working set of indexes must fit in RAM or reads go to disk);
  • build time on a large collection (build in the background, or on a secondary first).

The ESR rule: which fields, in which order

A compound index serves a query in one pass only when its fields are ordered Equality, Sort, Range. For { status: "PAID", placedAt: { $gte: since } } sorted by placedAt, the index is { status: 1, placedAt: -1 }. Equality first narrows to one contiguous run of the index. The sort field next means the run is already in sort order, so the range is a scan of a prefix of it.

Put the range field before the sort field, such as { status: 1, total: 1, placedAt: -1 } for a query with a range on total. Now the run is ordered by total, so the engine must fetch every matching document and sort in memory. That shows in the plan as a SORT stage, and it fails outright above 100 MB of results.

The rule is the same one the SQL index lesson gave for column order. MongoDB has a name for it.

A query uses the index whose prefix matches its fields: { a: 1, b: 1, c: 1 } serves { a }, { a, b }, { a, b, c } and not { b } or { b, c }. One well-ordered compound index replaces three single-field ones and serves the sort too; three single-field indexes may be intersected by the planner, and usually are not.

The aggregation pipeline

Anything past filter-project-sort is a pipeline: a list of stages, each transforming the stream of documents from the one before.

plaintext
db.orders.aggregate([
  { $match: { status: "PAID", placedAt: { $gte: since } } },          // FIRST, so an index applies
  { $unwind: "$lines" },                                               // one document per line
  { $group: { _id: "$lines.sku", qty: { $sum: "$lines.qty" }, revenue: { $sum: { $multiply: ["$lines.qty", "$lines.unitPaise"] } } } },
  { $sort: { revenue: -1 } },
  { $limit: 10 },
  { $lookup: { from: "products", localField: "_id", foreignField: "sku", as: "product" } },   // a join, after the limit
  { $project: { sku: "$_id", qty: 1, revenue: 1, name: { $first: "$product.name" } } }
])

$match and $sort at the front can use an index; after a $group or $unwind nothing can, so the rule is to filter first and reduce the stream before the expensive stages. $group is GROUP BY with accumulators ($sum, $avg, $min, $max, $push, $addToSet, $first); $unwind turns an array into one document per element, which is what makes grouping over array contents possible and what multiplies the stream by the array's length. $lookup is a left outer join, and it is a join with a join's cost — put it after the $limit, never before a $group over the whole collection, and give the foreign collection an index on foreignField. $facet runs several sub-pipelines on one input for a page that needs counts and a list; $merge writes the result into a collection, which is a materialised view on a schedule. A pipeline that is too slow to run per request is the CQRS lesson's projection, maintained as documents change.

Reading explain

db.orders.find({...}).sort({...}).explain("executionStats") is the plan. The lines that matter:

  • The winning plan's stages, read inside-out: IXSCAN on a named index feeding FETCH feeding SORT or LIMIT. A COLLSCAN anywhere is a query with no usable index.
  • totalKeysExamined against totalDocsExamined against nReturned. A healthy query examines about as many keys as it returns. A bad one examines a million documents to return twenty.
  • A SORT stage, which means the index did not provide the order and the ESR rule was broken.

The stage: "IXSCAN" block names indexBounds, so you can see that the range was applied on the index rather than after the fetch.

The SQL course's "the index that was there and not used" lesson applies line for line. A query on "customer.id" does not use an index on "customerId", a $regex without an anchored prefix cannot use one, and $ne and $nin scan.

Under the hood: a covered query, and what the aggregation optimizer actually does to your pipeline

A compound index does more than narrow which documents a query has to read. Under the right projection, it can answer the query without reading any document at all.

db.orders.find({"customer.id": id}, {_id: 0, "customer.id": 1, placedAt: 1}).explain("executionStats") against the {"customer.id": 1, placedAt: -1} index shows totalDocsExamined: 0. That happens when every field the query touches (the filter and the projection both) lives in the index itself. The server reads the answer straight out of the B-tree's leaf entries and never opens the collection.

This is a covered query, and the two conditions that make it possible are stricter than they look:

  • The projection must exclude _id explicitly. It is returned by default, and _id is not part of this compound index.
  • No field outside the index can appear in the projection or the filter, not one (not orderNumber for a log line). Otherwise the plan falls back to a normal IXSCAN + FETCH and pays for the document read anyway.

It is worth deliberately building a narrow index for a hot, narrow query (an existence check, a count, a lookup that only needs two fields) purely to get this. The cost is index size and write amplification. The return is a query that never touches the collection.

The aggregation pipeline you write is not the pipeline that runs. Before execution, MongoDB's aggregation optimizer rewrites the stage list:

  • A $match that appears after a $project or $addFields which does not touch the matched fields is moved earlier, past those stages. It can then use an index and shrink the stream before the expensive work rather than after.
  • A $sort immediately followed by a $limit is coalesced into a single top-k sort. It keeps only the k smallest or largest documents seen so far in a bounded structure, rather than sorting the entire input and truncating. That is the difference between memory proportional to k and memory proportional to the whole matched set.
  • A $match right after a $sort on the same field can sometimes let the engine stop pulling from the index early.

None of this is visible in the pipeline you wrote. explain() on the aggregation (not on a plain find) shows the actual stage list the server settled on, under stages. It is common for it to differ from the array in the code. That is the reason to read it rather than assume the pipeline runs top to bottom as literally written.

Some stages must see the whole input before producing any output:

  • $group cannot emit a group until every document that might belong to it has arrived.
  • $sort without a following $limit.
  • $bucket.

These cannot stream, so they buffer in memory. The server enforces a per-stage memory limit on that buffer (100 MB by default) and aborts the aggregation past it. The exception is a pipeline that sets {allowDiskUse: true}, which lets that one stage spill its working set to temporary files on disk and keep going, slower.

A pipeline that works in development on a sample collection and then fails in production with an "exceeded memory limit" error has not hit a different bug. It has hit a buffering stage whose input finally grew past 100 MB. allowDiskUse is the honest fix only when the alternative (an earlier $match or $limit to shrink what reaches that stage) genuinely is not available.

Try it yourself

Reason through whether a query is covered

An index exists on {status: 1, placedAt: -1}. Two queries run against orders:

  1. db.orders.find({status: "PAID"}, {_id: 0, status: 1, placedAt: 1})
  2. db.orders.find({status: "PAID"}, {_id: 0, status: 1, placedAt: 1, orderNumber: 1})
Only the first is a covered query

Query 1's filter (status) and its entire projection (status, placedAt, with _id explicitly excluded) are all fields present in the index {status: 1, placedAt: -1}. The server can answer it entirely from the index's leaf entries: totalDocsExamined will be 0 in explain("executionStats").

Query 2 asks for orderNumber in the projection, and orderNumber is not a field in this index at all. So the plan must still fetch the underlying document for every matching entry to retrieve it. That is an ordinary IXSCAN feeding a FETCH, not a covered query.

The index still narrows which documents are examined either way (both queries avoid a COLLSCAN), but only query 1 skips the collection read entirely. Adding one field to a projection that is not in the index is enough to lose that benefit.

Misconceptions

  • "Every $match in a pipeline can use an index." Only a $match the optimizer can place before any stage that transforms or reshapes documents, ideally the first stage as written, can use an index at all. A $match after a $group or $unwind filters the output of that stage, which is no longer the indexed collection's original documents. It runs as an in-memory filter regardless of what indexes exist.
  • "The pipeline runs exactly in the stage order it was written in." The aggregation optimizer reorders and merges adjacent stages — moving a movable $match earlier, coalescing $sort + $limit into a bounded top-k sort — before execution. explain() on the aggregation itself, not a guess from reading the code, is what shows the plan that actually ran.

Sources

  • MongoDB Manual, "Query Plans" and "Covered Query" (covered queries, totalDocsExamined, the ESR rule).
  • MongoDB Manual, "Aggregation Pipeline Optimization" (stage reordering and coalescing, $sort + $limit).
  • MongoDB Manual, "Aggregation Pipeline Limits" (the 100 MB per-stage memory limit and allowDiskUse).
Progress is saved on this device and to your account when signed in.