0
0
MongoDBquery~5 mins

$count accumulator in MongoDB

Choose your learning style9 modes available
Introduction

The $count accumulator helps you count how many items are in a group. It is like counting apples in a basket.

When you want to know how many orders a customer made.
When you want to count how many students passed a test.
When you want to find out how many products are in each category.
When you want to count how many times a word appears in a text.
When you want to see how many employees work in each department.
Syntax
MongoDB
{ $count: {} }

The $count accumulator does not take any arguments inside the braces.

It is used inside the $group stage of an aggregation pipeline.

Examples
This counts how many sales there are for each item.
MongoDB
db.sales.aggregate([
  { $group: { _id: "$item", totalCount: { $count: {} } } }
])
This counts how many students are in each class.
MongoDB
db.students.aggregate([
  { $group: { _id: "$class", passedCount: { $count: {} } } }
])
Sample Program

This example first adds some orders with different items. Then it counts how many orders there are for each item.

MongoDB
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: {} } } }
])
OutputSuccess
Important Notes

The $count accumulator is only available in MongoDB 5.0 and later.

It is simpler and clearer than using $sum: 1 to count documents.

Summary

$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.