Skip to content

Aggregation Fundamentals

$count

A dedicated stage for a single total, versus grouping when you still need the documents.

BeginnerAbout 3 minutes

$count emits one document: { <field>: <number> }. It is 'how many documents reached this stage?', not 'how many per city'. Per-key counts are $group + $sum: 1.

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $count: "completedOrders" }
])
How many completed orders?
{ completedOrders: 42 }

countDocuments({ status: "completed" }) is the same answer without a pipeline. Use $count when you are already in aggregate() — after a $match that was not a simple filter, or after $unwind. $count replaces the stream; you cannot $sort those orders afterwards in the same pipeline.

Interview question

When do you use $count instead of $group?

Think about it first.

Related lessons