Free tool

MongoDB aggregation explainer

Paste an aggregation pipeline, in JSON or mongosh syntax, and get a card for every stage right away, then a plain-English walkthrough of what the whole pipeline returns. Write stages and server-side JavaScript are flagged, and nothing is run.

  • No signup
  • Stage cards in your browser, narrative on request
  • 11 verified examples
164/20,000

3 stages on orders. Stage cards update as you type.

  1. 1$matchRead-only

    Keeps only the documents that pass a filter, like WHERE in SQL. Put it first so it can use an index.

    { $match: { status: { $ne: "cancelled" } } }
    $match in the MongoDB docs
  2. 2$groupRead-only

    Collapses documents that share a key into one row and computes totals, counts or averages, like GROUP BY.

    { $group: { _id: "$status", revenue: { $sum: "$total" } } }
    $group in the MongoDB docs
  3. 3$sortRead-only

    Orders documents by one or more fields; 1 ascending, -1 descending.

    { $sort: { revenue: -1 } }
    $sort in the MongoDB docs

Result on the sample data

Result on the sample data
_idrevenue
shipped37998
pending32496
delivered22096

Run this on your real database, read-only

Connect MongoDB with a read-only user and wuup writes, checks and runs queries like this for you, then answers with a chart or table.

Start free

11 worked examples,
run against real data

Every example ran on the sample orders, tickets, products collections before it was published, and the table under it is what MongoDB returned. Load any of them into the tool above.

Worked examples
  • aggregateorders01

    $match, $group, $sort

    “Revenue per status, without cancelled orders”

    db.orders.aggregate([
      { $match: { status: { $ne: "cancelled" } } },
      { $group: { _id: "$status", revenue: { $sum: "$total" } } },
      { $sort: { revenue: -1 } }
    ])
    • $match drops cancelled orders before any work is done.
    • $group collapses the remaining orders into one row per status with summed totals.
    Result of $match, $group, $sort on the sample data
    _idrevenue
    shipped37998
    pending32496
    delivered22096
  • aggregateorders02

    $unwind then $group

    “Units sold per SKU”

    db.orders.aggregate([
      { $match: { status: { $ne: "cancelled" } } },
      { $unwind: "$items" },
      { $group: { _id: "$items.sku", units: { $sum: "$items.qty" } } },
      { $sort: { units: -1, _id: 1 } }
    ])
    • $match keeps orders that were not cancelled.
    • $unwind splits each order into one document per line item in the items array.
    Result of $unwind then $group on the sample data
    _idunits
    KB-2014
    HP-3302
    MN-2702
    MS-1102
  • aggregateorders03

    $lookup, $unwind, $project

    “Delivered orders with the customer's name”

    db.orders.aggregate([
      { $match: { status: "delivered" } },
      {
        $lookup: {
          from: "customers",
          localField: "customerId",
          foreignField: "_id",
          as: "customer"
        }
      },
      { $unwind: "$customer" },
      {
        $project: { _id: 0, orderNumber: 1, total: 1, customer: "$customer.name" }
      },
      { $sort: { orderNumber: 1 } }
    ])
    • $match keeps delivered orders only.
    • $lookup finds the customer whose _id equals the order's customerId and stores it as an array.
    Result of $lookup, $unwind, $project on the sample data
    orderNumbertotalcustomer
    A-10019097Aarav Mehta
    A-100312999Sofia Rossi
  • aggregateorders04

    $facet with two sub-pipelines

    “Order counts per status and overall totals in one query”

    db.orders.aggregate([
      {
        $facet: {
          byStatus: [{ $sortByCount: "$status" }, { $sort: { count: -1, _id: 1 } }],
          totals: [
            {
              $group: { _id: null, orders: { $sum: 1 }, revenue: { $sum: "$total" } }
            }
          ]
        }
      }
    ])
    • $facet runs two independent pipelines over the same input and returns a single document.
    • byStatus uses $sortByCount (a group by status plus a count, sorted descending), then a $sort to break ties.

    Result depends on when it runs ($$NOW or $sample), so no fixed preview.

  • aggregateorders05

    $setWindowFields running total

    “Running revenue total in order date”

    db.orders.aggregate([
      { $match: { status: { $ne: "cancelled" } } },
      {
        $setWindowFields: {
          sortBy: { createdAt: 1 },
          output: {
            runningRevenue: { $sum: "$total", window: { documents: ["unbounded", "current"] } }
          }
        }
      },
      { $project: { _id: 0, orderNumber: 1, total: 1, runningRevenue: 1 } }
    ])
    • $match removes cancelled orders.
    • $setWindowFields sorts by createdAt and sums total from the first document up to the current one.
    Result of $setWindowFields running total on the sample data
    orderNumbertotalrunningRevenue
    A-10031299912999
    A-1001909722096
    A-10023799860094
    A-10053249692590
  • aggregateorders06

    $addFields with $dateDiff

    “Days from order to delivery”

    db.orders.aggregate([
      { $match: { deliveredAt: { $exists: true } } },
      {
        $addFields: {
          daysToDeliver: {
            $dateDiff: { startDate: "$createdAt", endDate: "$deliveredAt", unit: "day" }
          }
        }
      },
      { $project: { _id: 0, orderNumber: 1, daysToDeliver: 1 } },
      { $sort: { daysToDeliver: -1 } }
    ])
    • $match keeps orders that have a deliveredAt date.
    • $addFields adds daysToDeliver: the number of day boundaries between the two dates.
    Result of $addFields with $dateDiff on the sample data
    orderNumberdaysToDeliver
    A-10036
    A-10013
  • aggregatetickets07

    $sortByCount on an array

    “Which tags appear on the most tickets?”

    db.tickets.aggregate([
      { $unwind: "$tags" },
      { $sortByCount: "$tags" },
      { $sort: { count: -1, _id: 1 } }
    ])
    • $unwind emits one document per tag.
    • $sortByCount groups by tag, counts each and sorts by that count.
    Result of $sortByCount on an array on the sample data
    _idcount
    orders2
    account1
    billing1
  • aggregatetickets08

    $lookup then $replaceWith

    “Open tickets reshaped with the customer's name and plan”

    db.tickets.aggregate([
      { $match: { status: "open" } },
      { $sort: { ticketNumber: 1 } },
      {
        $lookup: {
          from: "customers",
          localField: "customerId",
          foreignField: "_id",
          as: "customer"
        }
      },
      {
        $replaceWith: {
          ticket: "$ticketNumber",
          priority: "$priority",
          customer: { $first: "$customer.name" },
          plan: { $first: "$customer.plan" }
        }
      }
    ])
    • $match and $sort pick open tickets in ticket-number order.
    • $lookup attaches the matching customer document as an array.
    Result of $lookup then $replaceWith on the sample data
    ticketprioritycustomerplan
    T-5001highPriya Nairbusiness
    T-5005urgentPriya Nairbusiness
  • aggregateorders09

    $unionWith activity timeline

    “One customer's orders and tickets in a single timeline”

    db.orders.aggregate([
      {
        $project: {
          _id: 0,
          customerId: 1,
          type: { $literal: "order" },
          ref: "$orderNumber",
          at: "$createdAt"
        }
      },
      {
        $unionWith: {
          coll: "tickets",
          pipeline: [
            {
              $project: {
                _id: 0,
                customerId: 1,
                type: { $literal: "ticket" },
                ref: "$ticketNumber",
                at: "$createdAt"
              }
            }
          ]
        }
      },
      { $match: { customerId: ObjectId("64f1a0c2e4b0a1b2c3d4e502") } },
      { $sort: { at: -1 } }
    ])
    • $project reshapes orders into timeline rows with a type, a reference and a timestamp.
    • $unionWith appends tickets reshaped the same way, like SQL UNION ALL.
    Result of $unionWith activity timeline on the sample data
    typeref
    ticketT-5005
    ticketT-5001
    orderA-1005
    orderA-1002
  • aggregateproducts10

    $match then $count

    “How many listed products are low on stock?”

    db.products.aggregate([
      { $match: { active: true, stock: { $lt: 10 } } },
      { $count: "lowStock" }
    ])
    • $match keeps active products with fewer than 10 units.
    • $count returns a single document with the number of matches in a field named lowStock.
    Result of $match then $count on the sample data
    lowStock
    2
  • aggregateproducts11

    $group with $topN

    “The two most expensive products in each category”

    db.products.aggregate([
      {
        $group: {
          _id: "$category",
          top: { $topN: { n: 2, sortBy: { price: -1 }, output: "$name" } }
        }
      },
      { $sort: { _id: 1 } }
    ])
    • $group makes one row per category.
    • $topN keeps the names of the 2 highest-priced products in each group, in price order.
    Result of $group with $topN on the sample data
    _idtop
    accessoriesMechanical keyboard, Wireless mouse
    audioNoise-cancelling headphones
    displays27-inch 4K monitor

How the tool works

Four steps, and none of them touch your database.

  1. 1

    Paste a pipeline

    JSON, relaxed JSON or a full db.collection.aggregate([...]) call from mongosh all work.

  2. 2

    See every stage

    Stage cards appear instantly in your browser, with a description and a link to the MongoDB docs.

  3. 3

    Get the walkthrough

    Ask for the narrative to get a summary, per-stage explanation with your real field names and performance notes.

  4. 4

    Spot the risks

    $out, $merge, $function and $where are flagged before you run anything.

What it won't do

Honest limits, so you know what to expect.

  • Execute or rewrite your pipeline.
  • Know your indexes. Performance notes are general advice; run explain() for the real plan.
  • Send anything until you ask for the walkthrough. Stage cards are built locally.

The same guard as the product

Generated queries pass the check wuup runs on every connected database: only read stages, no server-side JavaScript, at most 30 stages.

Writes ($out, $merge)
Refused
Server JS ($where, $function)
Refused
Stages
Read-only allowlist
Your database
Never contacted
Inputs
Cached 7 days by hash

The concepts
behind the output

A short explanation of what the tool produces and the mistakes it is built to avoid.

Reading a pipeline from top to bottom

Read a pipeline like a recipe: each stage receives the output of the one above it. Track the shape of the documents as you go. After a $group, the original fields are gone and only _id and the accumulators remain. After an $unwind, one document has become many.

The stage cards show this shape change for each step, and the walkthrough names your actual fields.

Stages that deserve a second look

$out and $merge write to a collection. $function, $accumulator and $where run JavaScript on the server. $lookup without an index on the foreign field and $group or $sort over a whole collection are the most common causes of slow pipelines.

Keep going

Guides that go deeper, the product that runs these queries for you, and the other free tools.

Questions,
answered

Stop writing queries.
Start asking wuup.