December 18, 2026 · Advent of MongoDB
18. Caught in the act Solved
Hard$lookup with pipelinelet
Being in the building isn't enough. Who was inside the Logistics Bay at the exact moment each fake entry was typed?
Your task
An elf was inside at the moment of an entry when their latest door swipe at or before that moment was an 'in' at the 'Logistics Bay'. For each fake entry (night entries on LOGI-07), find who was inside. Return elf and entries (how many fake entries they were inside for), most first, then by name.
Your answer returns 1 document with the fields elf, entries. Order matters.
What happens next
One elf. Every single entry. Grizzle Pinecone. Flurry was always on the far side of a door. You have the who. Pepper asks the obvious question: "But why would Grizzle do this?"
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
$lookup into doorSwipes with let: { t: "$loggedAt" } and a pipeline: $match swipes with $lte: ["$swipedAt", "$$t"], $sort newest first, $group by elf taking $first door and direction.Common traps
- Only the latest swipe counts: Flurry swipes into the bay every hour, but also out again a few minutes later.
Solution
db.niceListLog.aggregate([
{ $match: { terminal: "LOGI-07", $expr: { $lt: [{ $hour: "$loggedAt" }, 5] } } },
{ $lookup: {
from: "doorSwipes", let: { t: "$loggedAt" },
pipeline: [
{ $match: { $expr: { $lte: ["$swipedAt", "$$t"] } } },
{ $sort: { swipedAt: -1 } },
{ $group: { _id: "$elfId", door: { $first: "$door" }, direction: { $first: "$direction" } } },
{ $match: { door: "Logistics Bay", direction: "in" } }
],
as: "inside"
} },
{ $unwind: "$inside" },
{ $group: { _id: "$inside._id", entries: { $sum: 1 } } },
{ $lookup: { from: "elves", localField: "_id", foreignField: "_id", as: "e" } },
{ $project: { _id: 0, elf: { $first: "$e.name" }, entries: 1 } },
{ $sort: { entries: -1, elf: 1 } }
])
Free to play. Please don't republish the puzzles or solutions. See the Playground License Terms. Also on Advent of SQL.