aggregate()

Processes data through a pipeline of stages for grouping, filtering, projecting, and transforming documents.

Syntax

mongodb
db.collection.aggregate([stage1, stage2, ...])

Example

mongodb
db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: {
    _id: "$customerId",
    totalSpent: { $sum: "$amount" },
    orderCount: { $count: {} }
  }},
  { $sort: { totalSpent: -1 } },
  { $limit: 10 }
])