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 use unwind in MongoDB?
- How to remove a field from MongoDB?
- How to check the version of MongoDB?
- How to update an array element in MongoDB?
- What is MongoDB default port?
- How to perform a health check for MongoDB?
- How to use triggers in MongoDB?
- How to drop a database in MongoDB?
- How to check if array is empty in MongoDB?
See more codes...