Trung BìnhMongoDB iconMongoDB

Aggregation pipeline trong MongoDB dùng khi nào?

Aggregation pipeline xử lý data qua nhiều stages như $match, $group, $project, $sort, $lookup, $unwind. Nó phù hợp reporting, transformation, analytics nhẹ và server-side data shaping.

Ví dụ tính revenue theo ngày:

javascript
db.orders.aggregate([
  { $match: { status: "paid" } },
  { $group: { _id: "$day", revenue: { $sum: "$total" } } },
  { $sort: { _id: 1 } }
])

Đặt $match sớm để giảm dữ liệu đi qua pipeline và tận dụng index.

Xem toàn bộ MongoDB cùng filter theo level & chủ đề con.

Mở danh sách MongoDB