Aggregation $count
$count counts the documents that reach it and outputs one document with the count stored in a field whose name you choose:
{ $count: '<output field name>' }Counting matches
print(db.orders.aggregate([
{ $match: { status: 'delivered' } },
{ $count: 'deliveredOrders' }
]).toArray());[ { deliveredOrders: 10 } ]
It is a shorthand for a $group with _id: null and $sum: 1, followed by removing the _id:
print(db.orders.aggregate([
{ $match: { status: 'delivered' } },
{ $group: { _id: null, deliveredOrders: { $sum: 1 } } },
{ $project: { _id: 0 } }
]).toArray());[ { deliveredOrders: 10 } ]
Counting computed things
The power of $count is that it counts whatever the pipeline has produced, not just stored documents. How many line items were sold in total, and how many distinct customers have ordered?
print(db.orders.aggregate([{ $unwind: '$items' }, { $count: 'lineItems' }]).toArray());
print(db.orders.aggregate([
{ $group: { _id: '$customerId' } },
{ $count: 'customersWithOrders' }
]).toArray());[ { lineItems: 36 } ]
[ { customersWithOrders: 9 } ]
When nothing matches
If no document reaches $count, it outputs nothing at all, not a document with 0. Handle that in your code:
const res = db.orders.aggregate([
{ $match: { status: 'returned' } },
{ $count: 'n' }
]).toArray();
print(res);
print('returned orders:', res.length ? res[0].n : 0);[]
returned orders: 0
Counting per group
To count per category, status and so on, you need $group with $sum: 1 (or $count: {}) instead: $count the stage always produces a single total. The $sortByCount stage combines grouping, counting and sorting:
print(db.products.aggregate([
{ $unwind: '$tags' },
{ $sortByCount: '$tags' },
{ $sort: { count: -1, _id: 1 } }, // break ties by name
{ $limit: 4 }
]).toArray());[
{ _id: 'brewing', count: 4 },
{ _id: 'electric', count: 3 },
{ _id: 'sweet', count: 3 },
{ _id: 'whole-bean', count: 3 }
]
Note:
$sortByCountsorts by count only, so groups with equal counts may come in any order. The extra$sortabove breaks the ties alphabetically, so the result is the same on every run.
Which count should I use?
| Need | Use |
|---|---|
| number of documents matching a filter | db.coll.countDocuments(filter) |
| rough total of a big collection, instantly | db.coll.estimatedDocumentCount() |
| count the result of a pipeline | { $count: 'n' } |
| a count per group | $group with $sum: 1, or $sortByCount |
Test yourself
What does { $count: 'total' } output when 7 documents reach it?
- 7 documents
{ total: 7 }{ _id: null, total: 7 }7
What does a pipeline ending in $count return when no document matches?
[{ n: 0 }]- An empty result
null- An error