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);