CoreMedium$sum on arrays$project$match after $project
Merchandising wants to discount products that are sitting on too much stock. Stock for each product is split across warehouses in a stock array. Return every active product holding more than 160 units in total across all warehouses, with sku, name, totalStock and the number of warehouses that carry it. Sort by totalStock descending, then sku. (Discontinued products are cleared out separately.)
Your answer returns 8 documents with the fields name, sku, totalStock, warehouses. Order matters.
The data
The shop database from the MongoDB playground, running in your browser. "Today" is 2026-11-18.
categories18 docs
_id
ObjectId
name
string
parentId
null | ObjectId
path
string
suppliers6 docs
_id
ObjectId
name
string
country
string
rating
double
since
date
products26 docs
_id
ObjectId
sku
string
name
string
categoryId
ObjectId
supplierId
ObjectId
price
decimal
tags
array of string
stock
array of objects
warehouseqty
active
boolean
createdAt
date
customers30 docs
_id
ObjectId
name
string
email
string
tier
string
addresses
array of objects
typestreetcitycountryziplocation
preferences
object
newslettercurrency
lifetimeValue
decimal
joinedAt
date
marketingOptIn
boolean
phone
string, 24 of 30
lastLogin
date, 15 of 30
externalRef
int | string, 10 of 30
loyaltyPoints
int, 18 of 30
referredBy
ObjectId, 17 of 30
orders220 docs
_id
ObjectId
number
string
customerId
ObjectId
placedAt
date
status
string
statusHistory
array of objects
statusat
items
array of objects
productIdskunameqtyunitPrice
shipping
object
typestreetcitycountryziplocationmethod
total
decimal
currency
string
supportAgentId
ObjectId, 33 of 220
note
string, 33 of 220
reviews87 docs
_id
ObjectId
productId
ObjectId
customerId
ObjectId
orderId
ObjectId
rating
int
comment
string
at
date
employees9 docs
_id
ObjectId
name
string
title
string
reportsTo
null | ObjectId
Hints
Hint 1.$sum accepts an array: { $sum: "$stock.qty" } adds every element.
Hint 2. You can only filter on totalStock after you have computed it.
Common traps
Forgetting active: true: one discontinued product is heavily overstocked and sneaks into the list.
Ties: two products hold exactly 172 units, so the sku tie-breaker decides their order.
Free for personal practice. Please don't republish the questions or solutions. See the Playground License Terms.
Run in the shell with Ctrl/⌘ + Enter. Check with Shift + Ctrl/⌘ + Enter.
"Check answer" runs your shell code on a fresh copy of the data, then on 2 hidden test datasets with more customers and orders, and compares each result with the expected one. The value of your last line is your answer.