mongodbHow to group in MongoDB?
MongoDB provides the $group
aggregation operator to group documents by a specified key and perform accumulator operations.
Example
db.collection.aggregate([
{
$group: {
_id: "$department",
totalSalary: { $sum: "$salary" }
}
}
])
Output example
{ "_id" : "IT", "totalSalary" : 30000 }
{ "_id" : "HR", "totalSalary" : 15000 }
The $group
operator has the following parts:
_id
: The key to group documents by.totalSalary
: The accumulator expression to perform operations on the grouped documents.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- What is MongoDB default port?
- How to use transactions in MongoDB?
- How to list MongoDB users?
- How to use regex in MongoDB?
- How to use MongoDB push?
- How to query with "not equal" condition in MongoDB?
- How to empty an array in MongoDB?
- How to use triggers in MongoDB?
- How to check the version of MongoDB?
See more codes...