MongoDB 8 cheatsheet

MongoDB 8: Aggregation

5 common MongoDB 8 tasks.

Group and total

Sum order amounts per status.

db.orders.aggregate([
  { $group: { _id: "$status", total: { $sum: "$amount" }, count: { $sum: 1 } } }
])

Filter, sort and limit

Run $match early so the pipeline processes fewer documents.

db.orders.aggregate([
  { $match: { status: "paid" } },
  { $sort: { amount: -1 } },
  { $limit: 5 }
])

Join another collection

Add matching users to each order, like a left outer join.

db.orders.aggregate([
  { $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } }
])

Flatten an array

Output one document per array element.

db.orders.aggregate([{ $unwind: "$items" }])

Reshape documents

Keep some fields and compute new ones.

db.users.aggregate([
  { $project: { name: 1, domain: { $arrayElemAt: [{ $split: ["$email", "@"] }, 1] } } }
])

Was this page helpful?