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,_id
is set tonull
to 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 check the version of MongoDB?
- How to use watch in MongoDB?
- How to use unwind in MongoDB?
- How to insert new document into MongoDB?
- How to perform a health check for MongoDB?
- How to use triggers in MongoDB?
- How to work with time series data in MongoDB?
- How to list MongoDB users?
- How to update an array element in MongoDB?
- How to update many documents in MongoDB?
See more codes...