0% completed
The $count
stage in MongoDB's aggregation framework is used to count the number of documents that pass through the pipeline. It is a simple and efficient way to obtain the count of documents that match specific criteria. This stage is often used in reporting and data validation scenarios to quickly tally the number of documents that meet certain conditions.
{ $count: "<field>" }
First, let's insert some documents into the orders
collection to work with:
db.orders.insertMany([ { order_id: 1, product: "apple", quantity: 10, status: "completed" }, { order_id: 2, product: "banana", quantity: 5, status: "pending" }, { order_id: 3, product: "orange", quantity: 8, status: "completed" }, { order_id: 4, product: "apple", quantity: 15, status: "pending" }, { order_id: 5, product: "banana", quantity: 7, status: "completed" } ])
Count the number of documents in the orders
collection.
Pipeline:
db.orders.aggregate([ { $count: "totalOrders" } ])
Explanation:
totalOrders
.This command results in an output like:
{ "totalOrders": 5 }
Count the number of completed orders.
Pipeline:
db.orders.aggregate([ { $match: { status: "completed" } }, { $count: "completedOrders" } ])
Explanation:
status
is "completed".completedOrders
.This command results in an output like:
{ "completedOrders": 3 }
Count the number of different products ordered.
Pipeline:
db.orders.aggregate([ { $group: { _id: "$product" } }, { $count: "uniqueProducts" } ])
Explanation:
product
field, resulting in distinct groups for each product.uniqueProducts
.This command results in an output like:
{ "uniqueProducts": 3 }
The $count
stage is a straightforward yet powerful tool in MongoDB's aggregation framework. It allows you to quickly count the number of documents that pass through the pipeline, making it useful for data validation, reporting, and simple analytics.
.....
.....
.....