Sikau

MongoDB · Day 12 · about 35 min

$unwind and $lookup

Open up arrays and join collections.

Inside arrays, across collections

"Revenue per dish" lives inside each order's items array. $unwind turns each array element into its own document so you can group them. $lookup pulls in matching documents from another collection — MongoDB's join.

Unwind, group, look up

printjson(db.orders.aggregate([
  { $match: { status: "served" } },
  { $unwind: "$items" },
  { $group: { _id: "$items.dish", sold: { $sum: "$items.qty" }, revenue: { $sum: { $multiply: ["$items.qty", "$items.price"] } } } },
  { $sort: { revenue: -1 } },
]));

printjson(db.orders.aggregate([
  { $match: { status: "served" } },
  { $lookup: { from: "customers", localField: "customer", foreignField: "_id", as: "who" } },
  { $project: { _id: 0, name: { $first: "$who.name" }, lines: { $size: "$items" } } },
]));

The rest of this lesson

  • $lookup step by stepexplain
  • Unwind with careexplain
  • Documents after $unwind?predict
  • Counting after unwindpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of MongoDB