mongodbHow to aggregate in MongoDB?
MongoDB provides several ways to aggregate data from collections. The most common way is to use the aggregate()
method. This method takes an array of pipeline stages as its argument and returns the aggregated result.
Example
db.collection.aggregate([
{
$group: {
_id: "$department",
totalSalary: { $sum: "$salary" }
}
}
])
Output example
{ "_id" : "IT", "totalSalary" : 15000 }
{ "_id" : "HR", "totalSalary" : 12000 }
Code explanation
aggregate()
: The method used to aggregate data from collections.$group
: The operator used to group documents by a specified field and perform an aggregation on them._id
: The field used to specify the field to group by.$sum
: The operator used to sum the values of a specified field.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- What is MongoDB default port?
- How to perform a health check for MongoDB?
- How to list all indexes in MongoDB?
- How to use eq in MongoDB?
- How to update one document in MongoDB?
- How to order query results in MongoDB?
- How to check if array is empty in MongoDB?
- How to query with "not equal" condition in MongoDB?
- How to use transactions in MongoDB?
See more codes...