$count (Count)
Last updated: 2026-10-09
$count (Count)
$count returns a single document shaped like { field: N } holding the number of documents remaining in the pipeline. It is shorthand for $group with $sum: 1. Placed after $match it counts filtered results without grouping. The output is a single document that any later stage sees.
| Category | Core Stages |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $count: "<outputFieldName>" }
⚙️ Parameters
| output field name | The field name that receives the count. |
|---|
Returns:A single { count: N } document (field name from the argument)
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $count: number of orders with status A
db.orders.aggregate([
{ $match: { status: 'A' } },
{ $count: 'total' }
])
Output:
// Number of matched orders
{ "total": 25 }
📌 Notes
- $count emits a single document; only one flows onward
- Equivalent to { $group: { _id: null, count: { $sum: 1 } } }
- The field name must be a plain string, not a $-prefixed path
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $count and countDocuments?
AcountDocuments counts the collection directly; $count tallies what previous pipeline stages produced.
QCan aggregation continue after $count?
AYes. It emits one document, which later stages keep processing.
QCan $count rename its output field?
AYes, the argument is the field name, e.g. { $count: 'total' } yields { total: N }.