December 15, 2026 · Advent of MongoDB
15. Cookie fuel Solved
Medium$setWindowFieldsdocuments window
An investigation runs on cookies. Cocoa Sugarplum in the Kitchen wants to know if the investigators are eating more than usual. Every batch is in cookieBatches; the Kitchen bakes every single day.
Your task
Total the cookies per day, and add a 3-day moving average (that day and the two before it). Return day (a "YYYY-MM-DD" string), cookies and avg3d for November 24 to 30, in date order.
Your answer returns 7 documents with the fields day, cookies, avg3d. Order matters.
What happens next
Cocoa nods. "Normal. Except the Logistics night crew: on a few nights they took a whole tin. And they never work nights in November." You thank her and head for the security office.
Solve today's puzzle to read what happens next.
The data
The North Pole's collections, a snapshot taken on December 1, 2026. Times are North Pole time (UTC). A MongoDB-compatible database runs in your browser: use Explore data to browse it.
elves_id, name, department, hiredOn, managerId (→ elves._id, null for the Head Elf), leave: [{ from, to }]children_id, name, country, city, utcOffset, age, wishlist: [toy _id, …] (top wish first)toys_id, name, category, buildMinutes, weightGniceListLog_id, childId, loggedAt, points, reason, recordedBy (→ elves._id), terminal (→ terminals._id)terminals_id (e.g. "LOGI-07"), location, departmentreindeer_id, name, maxLoadKgflights_id, reindeerId, flownOn, km, carrotsbuilds_id, toyId, elfId, builtAt, minutes, passedQccookieBatches_id, bakedAt, elfId, cookiesdoorSwipes_id, elfId, swipedAt, door, direction ("in" or "out")
Hints
$setWindowFields sorted by day, with window: { documents: [-2, 0] }.Common traps
- Filtering to November 24 first leaves the 24th and 25th without the days before them, so their averages come out wrong.
Solution
db.cookieBatches.aggregate([
{ $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$bakedAt" } }, cookies: { $sum: "$cookies" } } },
{ $setWindowFields: { sortBy: { _id: 1 }, output: { avg3d: { $avg: "$cookies", window: { documents: [-2, 0] } } } } },
{ $match: { _id: { $gte: "2026-11-24" } } },
{ $project: { _id: 0, day: "$_id", cookies: 1, avg3d: 1 } },
{ $sort: { day: 1 } }
])
Free to play. Please don't republish the puzzles or solutions. See the Playground License Terms. Also on Advent of SQL.