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?
- How to check the version of MongoDB?
- How to update one document in MongoDB?
- How to use unwind in MongoDB?
- How to use triggers in MongoDB?
- How to list MongoDB users?
- How to update an array element in MongoDB?
- How to bind IP addresses for MongoDB server?
- How to work with time series data in MongoDB?
- How to update many documents in MongoDB?
See more codes...