mongodbHow to count aggregated results in MongoDB?
MongoDB provides the $group aggregation operator to group documents by a specified key and apply accumulator expressions. The $group operator can be used to count the number of documents in a collection or the number of documents that match a specific criteria.
Example code
db.collection.aggregate([
{
$group: {
_id: null,
count: { $sum: 1 }
}
}
])
Output example
{ "_id" : null, "count" : 5 }
Code explanation
$group: This is the aggregation operator used to group documents by a specified key._id: This is the field used to specify the key to group documents by. In this example,_idis set tonullto group all documents together.count: This is the field used to store the result of the accumulator expression.$sum: This is the accumulator expression used to count the number of documents.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- How to use unwind in MongoDB?
- How to rename a field in MongoDB?
- How to insert new document into MongoDB?
- How to remove a field from MongoDB?
- How to use triggers in MongoDB?
- How to do text search in MongoDB?
- How to use transactions in MongoDB?
- How to find by id in MongoDB?
- How to check the version of MongoDB?
See more codes...