December 12, 2026 · Advent of MongoDB
12. Quality control Solved
Medium$cond$divide$sort
Back in the workshop, Bramble Gumdrop is fuming over a pile of wobbly rocking horses. Every finished toy is in builds, and passedQc says whether it passed quality control.
Your task
Among elves with at least 20 builds, find the 3 with the highest failure rate (failed builds ÷ builds). Return elf, builds and failed, highest rate first, ties by name.
Your answer returns 3 documents with the fields elf, builds, failed. Order matters.
What happens next
The top name on your list blushes to the tips of their ears. "My glue gun's been possessed since Halloween!" Not a crime, then. Just a glue gun. Back to the case.
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
Common traps
- Sort on the ratio before you
$projectit away.
Solution
db.builds.aggregate([
{ $group: { _id: "$elfId", builds: { $sum: 1 }, failed: { $sum: { $cond: ["$passedQc", 0, 1] } } } },
{ $match: { builds: { $gte: 20 } } },
{ $lookup: { from: "elves", localField: "_id", foreignField: "_id", as: "e" } },
{ $project: { _id: 0, elf: { $first: "$e.name" }, builds: 1, failed: 1, rate: { $divide: ["$failed", "$builds"] } } },
{ $sort: { rate: -1, elf: 1 } },
{ $limit: 3 },
{ $project: { rate: 0 } }
])
Free to play. Please don't republish the puzzles or solutions. See the Playground License Terms. Also on Advent of SQL.