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
readon 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
partitionBygroup spills to disk withallowDiskUse.