22. Counting Results with $count and Group Accumulators
$count counts documents that reach its position in the pipeline and emits a document containing the count. If no documents reach it, the pipeline produces no count document, so applications may need to handle an empty result.
Use $sum: 1 inside $group to count documents by group. Remember that after $unwind, you may be counting array elements rather than original parent documents. Define exactly what the report counts: orders, line items, distinct customers, or groups.
Code Example
db.orders.aggregate([
{ $match: { status: "delivered" } },
{ $count: "deliveredOrderCount" }
]);
db.orders.aggregate([
{ $match: { status: "delivered" } },
{ $unwind: "$items" },
{ $group: { _id: "$items.category", lineItemCount: { $sum: 1 }, unitsSold: { $sum: "$items.quantity" } } },
{ $sort: { lineItemCount: -1, _id: 1 } }
]);Key Takeaways
- $count counts current pipeline documents.
- $sum: 1 counts records within groups.
- After $unwind, counts may represent items.
- Handle empty input explicitly.
Knowledge Check
What does $count measure after $unwind?