MongoDB Exercises
Time to practise on the TAD Coffee sample data. Each exercise has a starter playground that runs as it is and prints a placeholder result. Replace the TODO parts, compare your output with the expected result, and open the solution only after a real attempt. Remember that each run starts from a fresh copy of the sample database.
| # | Exercise | Topics |
|---|---|---|
| 1 | Coffee in stock | filters, projection, sort |
| 2 | American customers with an email | dot notation, $exists |
| 3 | Tea sale | updateMany, $mul, $addToSet |
| 4 | Monthly revenue | $match, $group, $month |
| 5 | Best-selling products by revenue | $unwind, $group, $sort, $limit |
| 6 | What gold customers spent | $lookup, array sums |
| 7 | Shopping cart | positional $, upsert |
| 8 | Restock report | $project, $cond |
1. Coffee in stock
List the coffees that are in stock (stock greater than 0), showing only name and price (no _id), most expensive first.
Expected: 4 products, starting with { name: 'Ethiopia Yirgacheffe', price: 27 } and ending with { name: 'House Blend', price: 18 }.
// TODO: add the stock condition, a projection and a sort
print(db.products.find({ category: 'coffee' }).toArray().length);5
Show solution
print(db.products.find(
{ category: 'coffee', stock: { $gt: 0 } },
{ _id: 0, name: 1, price: 1 }
).sort({ price: -1 }).toArray());2. American customers with an email
Print the names (sorted alphabetically) of customers who live in the USA and have an email field.
Expected: [ 'Barbara Liskov', 'Grace Hopper', 'Katherine Johnson', 'Margaret Hamilton' ].
// TODO: filter on the embedded country and on the existence of email
print(db.customers.find({}).toArray().map(c => c.name).length, 'customers');12 customers
Show solution
print(db.customers.find({ 'address.country': 'USA', email: { $exists: true } })
.sort({ name: 1 }).toArray().map(c => c.name));Donald Knuth, Linus Torvalds and Radia Perlman live in the USA but have no email.
3. Tea sale
In one updateMany, reduce the price of every tea by 10% and add the tag 'sale' (without creating duplicates if the update runs twice). Then print each tea's name and price with two decimals, ordered by _id.
Expected:
Green Sencha 10.80
Earl Grey 8.55
Chamomile Calm 7.20
Masala Chai 9.90// TODO: one updateMany with two update operators
db.products.find({ category: 'tea' }).sort({ _id: 1 }).forEach(p => print(p.name, p.price.toFixed(2)));Green Sencha 12.00
Earl Grey 9.50
Chamomile Calm 8.00
Masala Chai 11.00
Show solution
db.products.updateMany({ category: 'tea' }, { $mul: { price: 0.9 }, $addToSet: { tags: 'sale' } });
db.products.find({ category: 'tea' }).sort({ _id: 1 }).forEach(p => print(p.name, p.price.toFixed(2)));4. Monthly revenue
Ignoring cancelled orders, compute the number of orders and the revenue (sum of total) per month number, sorted by month.
Expected: four groups, from { _id: 3, orders: 7, revenue: 385.5 } to { _id: 6, orders: 2, revenue: 82.5 }.
print(db.orders.aggregate([
// TODO: $match, then $group by { $month: '$date' }, then $sort
{ $count: 'orders' }
]).toArray());[ { orders: 20 } ]
Show solution
print(db.orders.aggregate([
{ $match: { status: { $ne: 'cancelled' } } },
{ $group: { _id: { $month: '$date' }, orders: { $sum: 1 }, revenue: { $sum: '$total' } } },
{ $sort: { _id: 1 } }
]).toArray());5. Best-selling products by revenue
Using the line items of non-cancelled orders, find the three products that brought in the most money (qty × price). Group by the item name.
Expected: Burr Grinder (178), Espresso Beans (147), Ethiopia Yirgacheffe (108).
print(db.orders.aggregate([
{ $match: { status: { $ne: 'cancelled' } } },
// TODO: $unwind the items, $group by name with a $multiply inside $sum, $sort, $limit
{ $limit: 1 },
{ $project: { _id: 1 } }
]).toArray());[ { _id: 1001 } ]
Show solution
print(db.orders.aggregate([
{ $match: { status: { $ne: 'cancelled' } } },
{ $unwind: '$items' },
{ $group: { _id: '$items.name', revenue: { $sum: { $multiply: ['$items.qty', '$items.price'] } } } },
{ $sort: { revenue: -1, _id: 1 } },
{ $limit: 3 }
]).toArray());6. What gold customers spent
For each gold customer, print their name and the sum of the totals of all their orders (any status), biggest spender first.
Expected:
Barbara Liskov 180
Grace Hopper 178
Ada Lovelace 142.5db.customers.find({ tier: 'gold' }).forEach(c => {
// TODO: replace this loop with one aggregation using $lookup
print(c.name, 0);
});Ada Lovelace 0
Grace Hopper 0
Barbara Liskov 0
Show solution
db.customers.aggregate([
{ $match: { tier: 'gold' } },
{ $lookup: { from: 'orders', localField: '_id', foreignField: 'customerId', as: 'orders' } },
{ $project: { name: 1, spent: { $sum: '$orders.total' } } },
{ $sort: { spent: -1 } }
]).forEach(c => print(c.name, c.spent));'$orders.total' is the array of the joined orders' totals, and $sum adds up an array.
7. Shopping cart
Write addToCart(customerId, productId, qty) for a carts collection whose documents look like { _id: <customerId>, items: [{ productId, qty }] }. If the product is already in the cart, increase its qty; otherwise append it. A cart that doesn't exist yet must be created.
Expected after the three calls below: items: [ { productId: 3, qty: 3 }, { productId: 17, qty: 2 } ].
function addToCart(customerId, productId, qty) {
// TODO: try $inc with the positional operator; if nothing matched, $push with upsert
}
addToCart(1, 3, 1);
addToCart(1, 17, 2);
addToCart(1, 3, 2);
print(db.carts.findOne({ _id: 1 }));null
Show solution
function addToCart(customerId, productId, qty) {
const r = db.carts.updateOne(
{ _id: customerId, 'items.productId': productId },
{ $inc: { 'items.$.qty': qty } }
);
if (r.matchedCount === 0) {
db.carts.updateOne({ _id: customerId }, { $push: { items: { productId, qty } } }, { upsert: true });
}
}A single upsert with 'items.productId': productId in the filter doesn't work: when the cart exists but lacks the product, the filter matches nothing, so the upsert tries to insert a second cart with the same _id and fails with E11000.
8. Restock report
List every product with fewer than 10 units in stock: name, stock and a status that is 'sold out' for 0 and 'low' otherwise. Sort by stock, then name.
Expected: 7 products, the four sold-out ones first (Chamomile Calm, Colombia Supremo, Milk Frother, Oat Cookies), then Gooseneck Kettle (4), Burr Grinder (6) and French Press (9).
print(db.products.aggregate([
{ $match: { stock: { $lt: 10 } } },
// TODO: $project with $cond, then $sort
{ $count: 'lowStock' }
]).toArray());[ { lowStock: 7 } ]
Show solution
print(db.products.aggregate([
{ $match: { stock: { $lt: 10 } } },
{ $project: { _id: 0, name: 1, stock: 1, status: { $cond: [{ $eq: ['$stock', 0] }, 'sold out', 'low'] } } },
{ $sort: { stock: 1, name: 1 } }
]).toArray());Test yourself
Which update both lowers prices by 10% and adds a tag only once?
{ $set: { price: 0.9 }, $push: { tags: 'sale' } }{ $mul: { price: 0.9 }, $addToSet: { tags: 'sale' } }{ $inc: { price: -0.1 }, $push: { tags: 'sale' } }{ price: '$price * 0.9' }
In exercise 6, why does { $sum: '$orders.total' } work after $lookup?
- $sum adds up the numbers in an array
- $lookup computes the sum
- It only takes the first order
- It needs $unwind first