TExcelTAD
Home › MongoDB › Aggregation $count

Aggregation $count

$count counts the documents that reach it and outputs one document with the count stored in a field whose name you choose:

js
{ $count: '<output field name>' }

Counting matches

mongosh · try it yourself
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:

mongosh · try it yourself
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?

mongosh · try it yourself
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:

mongosh · try it yourself
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:

mongosh · try it yourself
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: $sortByCount sorts by count only, so groups with equal counts may come in any order. The extra $sort above 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?

  1. 7 documents
  2. { total: 7 }
  3. { _id: null, total: 7 }
  4. 7

What does a pipeline ending in $count return when no document matches?

  1. [{ n: 0 }]
  2. An empty result
  3. null
  4. An error