Sikau

Project: The café’s data · Day 4 · about 40 min

The same orders as documents

Embedded documents, updates with $set/$push, and aggregation pipelines.

Store it the way you read it

In MongoDB an order can be one document: the customer's details and the items embedded inside, read in a single fetch. Questions across many orders become an aggregation pipeline — stages that filter, unwind, group and reshape.

Write, update, aggregate

db.orders.insertOne({
  _id: 5,
  customer: { name: "Bikash", city: "Kathmandu" },
  status: "new",
  items: [{ dish: "Momo", price: 180, qty: 3 }],
});

db.orders.updateOne(
  { _id: 5 },
  { $set: { status: "served" }, $push: { items: { dish: "Masala tea", price: 50, qty: 1 } } },
);

const byCity = db.orders.aggregate([
  { $match: { status: "served" } },
  { $unwind: "$items" },
  { $group: { _id: "$customer.city", revenue: { $sum: { $multiply: ["$items.price", "$items.qty"] } } } },
  { $sort: { revenue: -1 } },
  { $project: { _id: 0, city: "$_id", revenue: 1 } },
]);
printjson(byCity);

const popular = db.orders.aggregate([
  { $match: { status: "served" } },
  { $unwind: "$items" },
  { $group: { _id: "$items.dish", qty: { $sum: "$items.qty" } } },
  { $sort: { qty: -1, _id: 1 } },
  { $limit: 2 },
]);
printjson(popular);

The rest of this lesson

  • The same data, a different shapeexplain
  • The revenue pipelineexplain
  • After $unwindpredict
  • SQL to MongoDBmatch
  • Orders as documentswrite code
  • Badge quizquiz
  • What you builtrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 5 lessons of Project: The café’s data