Bussola

A MongoDB Aggregation Cheat Sheet for Everyday Checks

Most operational questions about a MongoDB collection (“how many orders per status?”, “which emails are duplicated?”, “how many documents per day this week?”) can be answered with a pipeline of two to four stages. This page collects MongoDB aggregation examples for those everyday checks, written for mongosh, plus the stage-ordering rules that keep them fast. Each pipeline is read-only, so it is safe to run against production with a read-only user.

The examples assume an orders collection with documents like this:

{
  _id: ObjectId("..."),
  status: "shipped",
  customerId: ObjectId("..."),
  email: "ana@example.com",
  total: 74.5,
  createdAt: ISODate("2026-11-03T09:12:00Z")
}

Stage order: filter first, group later

An aggregation runs its stages in sequence, and the cheapest way to make one fast is to shrink the data early.

  • Put $match as early as possible. A $match at the very start of the pipeline can use an index, exactly like a find() filter.
  • A $sort at the start, or directly after a leading $match, can also use an index if one matches the sort keys. After a $group or $project that reshapes documents, it cannot.
  • $limit right after $sort lets the server keep only the top N documents in memory instead of sorting everything.
  • Use $project or $unset to drop large fields before expensive stages, though the optimizer often does part of this itself.
  • Check the plan with explain. See how to read explain output for what COLLSCAN and IXSCAN mean.
db.orders.explain("executionStats").aggregate([
  { $match: { status: "shipped" } },
  { $group: { _id: "$customerId", n: { $sum: 1 } } }
])

Note that $group and $sort stages have a memory limit per stage (100 MB by default in older versions). If a pipeline exceeds it, the server may error unless you pass allowDiskUse: true. Newer versions can spill to disk by default, so check your deployment.

Count documents by status

The classic. $sortByCount is shorthand for a $group on one field followed by a descending sort.

db.orders.aggregate([
  { $sortByCount: "$status" }
])

The explicit equivalent, which you can extend with more accumulators:

db.orders.aggregate([
  { $group: { _id: "$status", count: { $sum: 1 }, revenue: { $sum: "$total" } } },
  { $sort: { count: -1 } }
])

Documents without a status field are grouped under _id: null, which is often the first sign of a data quality problem.

To restrict to a time window, add a $match first, using a half-open range:

db.orders.aggregate([
  { $match: { createdAt: { $gte: ISODate("2026-11-01"), $lt: ISODate("2026-11-08") } } },
  { $sortByCount: "$status" }
])

Top N

Top customers by revenue:

db.orders.aggregate([
  { $match: { status: { $ne: "cancelled" } } },
  { $group: { _id: "$customerId", revenue: { $sum: "$total" }, orders: { $sum: 1 } } },
  { $sort: { revenue: -1 } },
  { $limit: 10 }
])

If you only need the N largest documents rather than groups, a plain find is simpler and can use an index:

db.orders.find({}, { total: 1, status: 1 }).sort({ total: -1 }).limit(10)

For the top N per group (say, the latest 3 orders per customer), pushing every document into an array builds unbounded arrays. In newer server versions, $topN does it directly:

db.orders.aggregate([
  { $group: {
      _id: "$customerId",
      latest: { $topN: { n: 3, sortBy: { createdAt: -1 }, output: "$_id" } }
  } }
])

$topN requires MongoDB 5.2 or later. On older versions, use $sort followed by $group with $push and $slice, and mind the 16 MB document limit.

Find duplicates by field

Group on the field that should be unique, keep groups with more than one member, and collect the _id values so you can inspect or delete them.

db.orders.aggregate([
  { $group: { _id: "$email", count: { $sum: 1 }, ids: { $push: "$_id" } } },
  { $match: { count: { $gt: 1 } } },
  { $sort: { count: -1 } },
  { $limit: 20 }
])

This scans the whole collection, so on a large one, run it off-peak or on a secondary. The $limit bounds the output, but not the work. For case-insensitive duplicates, group on { $toLower: "$email" }. For a combination of fields, use a compound key: _id: { email: "$email", customerId: "$customerId" }.

If you plan to add a unique index afterwards, this pipeline is exactly the check to run first: index creation fails while duplicates exist.

Documents missing a field

In a plain query, { field: null } matches both missing fields and explicit nulls, while { field: { $exists: false } } matches only missing ones. See the query operators cheat sheet for the full picture. To quantify the problem in one pass:

db.orders.aggregate([
  { $group: {
      _id: null,
      total: { $sum: 1 },
      missingEmail: { $sum: { $cond: [{ $eq: [{ $type: "$email" }, "missing"] }, 1, 0] } },
      nullEmail: { $sum: { $cond: [{ $eq: [{ $type: "$email" }, "null"] }, 1, 0] } },
      emptyEmail: { $sum: { $cond: [{ $eq: ["$email", ""] }, 1, 0] } }
  } }
])

$type returns the string "missing" for absent fields, which is what makes this distinction possible inside an expression. A related check, the distribution of BSON types for one field, often reveals numbers stored as strings:

db.orders.aggregate([
  { $group: { _id: { $type: "$total" }, count: { $sum: 1 } } }
])

Distribution per day

$dateTrunc (MongoDB 5.0 and later) truncates a date to a unit and supports a time zone:

db.orders.aggregate([
  { $match: { createdAt: { $gte: ISODate("2026-10-10T00:00:00Z") } } },
  { $group: {
      _id: { $dateTrunc: { date: "$createdAt", unit: "day", timezone: "Europe/Rome" } },
      count: { $sum: 1 }
  } },
  { $sort: { _id: 1 } }
])

Without timezone, days are cut at UTC midnight, which can put an evening order in the wrong day for your users. On older servers, use $dateToString with a format such as "%Y-%m-%d" and the same timezone option, which gives a string key instead of a date.

Days with zero documents do not appear in the output. If you need a gap-free series, fill the gaps client-side, or look at $densify (MongoDB 5.1 and later).

Sanity-check references with $lookup

To find recent orders whose customerId points at a customer that no longer exists:

db.orders.aggregate([
  { $match: { createdAt: { $gte: ISODate("2026-11-01") } } },
  { $lookup: {
      from: "customers",
      localField: "customerId",
      foreignField: "_id",
      as: "customer"
  } },
  { $match: { customer: { $size: 0 } } },
  { $project: { customer: 0 } },
  { $limit: 50 }
])

Keep the first $match selective, because $lookup runs once per input document. The lookup is fast when foreignField is indexed, and _id always is. Without such an index, every input document triggers a scan of the other collection. On sharded clusters, restrictions on the from collection depend on the server version, so check the documentation for yours.

Small pipelines, big collections

A few habits keep ad hoc checks from becoming incidents:

  1. Start with a $match and a $limit while you iterate; remove the limit only when the shape is right.
  2. Add maxTimeMS so a runaway pipeline is killed server-side: db.orders.aggregate(pipeline, { maxTimeMS: 15000 }).
  3. Avoid $out and $merge in checks. They write, and a read-only user cannot run them anyway.
  4. Prefer $count over $group when you just need a number: { $count: "n" } as the final stage.
  5. For a plain count of a whole collection, estimatedDocumentCount is much cheaper. The counting article explains the trade-off.

Quick reference

Question Stages
Count per value $sortByCount, or $group + $sort
Top N groups $group, $sort, $limit
Duplicates $group with $push, then $match on count
Missing / null / wrong type $group on { $type: "$field" }
Per-day volume $match on date, $group with $dateTrunc
Dangling references $match, $lookup, $match on $size: 0

When you are away from a laptop, the same pipelines work in any client that accepts a pipeline as text. Bussola can run aggregations on an iPhone, showing a live preview and document count after each stage, which is handy for confirming that a $match keeps the number of documents you expect before adding a $group.

mongodbaggregationmongoshcheat-sheet

Bussola is a free MongoDB client for iPhone: query, edit and aggregate over a direct connection, with no backend.

Coming soon to the App Store