Introduction
The $count accumulator helps you count how many items are in a group. It is like counting apples in a basket.
The $count accumulator helps you count how many items are in a group. It is like counting apples in a basket.
{ $count: {} }The $count accumulator does not take any arguments inside the braces.
It is used inside the $group stage of an aggregation pipeline.
db.sales.aggregate([
{ $group: { _id: "$item", totalCount: { $count: {} } } }
])db.students.aggregate([
{ $group: { _id: "$class", passedCount: { $count: {} } } }
])This example first adds some orders with different items. Then it counts how many orders there are for each item.
db.orders.insertMany([
{ item: "apple", quantity: 5 },
{ item: "banana", quantity: 3 },
{ item: "apple", quantity: 2 },
{ item: "banana", quantity: 4 },
{ item: "orange", quantity: 7 }
])
db.orders.aggregate([
{ $group: { _id: "$item", count: { $count: {} } } }
])The $count accumulator is only available in MongoDB 5.0 and later.
It is simpler and clearer than using $sum: 1 to count documents.
$count counts the number of documents in each group.
Use it inside $group stage in aggregation.
It does not need any arguments inside the braces.
$count accumulator do in a MongoDB aggregation pipeline?$count$count accumulator is used inside the $group stage to count how many documents belong to each group.$sum, $max, or $avg, $count does not operate on field values but counts documents.$count = document count [OK]$count in a $group stage?$count syntax$count accumulator does not take any arguments inside its braces; it should be empty: { $count: {} }.$count, which is invalid syntax.{ "category": "A" }, { "category": "B" }, { "category": "A" }[ { $group: { _id: "$category", count: { $count: {} } } } ]$count accumulator is not valid inside a $group stage. It is a separate pipeline stage used to count total documents, not per group.$sum: 1 inside $group, not $count.$count inside $group$count inside $group causes a syntax error.$count is a pipeline stage, not an accumulator [OK][ { $group: { _id: "$type", total: { $count: "$amount" } } } ]$count accumulator does not accept any arguments; passing "$amount" is invalid syntax.$count to achieve this?$count is not valid inside $group, use $sum: 1 to count documents per group.$match after grouping to filter customers with orderCount greater than 2.Pass the test and this pattern moves unknown