Window functions

Compute over neighbouring documents without grouping them, with $setWindowFields.

Compute over neighbouring documents without grouping them with $setWindowFields. It serves for running totals, moving averages or rankings.

Requirements

  • A connection with a user that has read on the database.

Running total per customer

JavaScript
db.orders.aggregate([
  {
    $setWindowFields: {
      partitionBy: "$customer",
      sortBy: { created: 1 },
      output: { runningTotal: { $sum: "$total", window: { documents: ["unbounded", "current"] } } },
    },
  },
]);

Check

Each order carries in runningTotal the sum of its customer's orders up to it.

Common problems

  • A window over a very large partitionBy group spills to disk with allowDiskUse.

See also