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 check the version of MongoDB?
- How to use watch in MongoDB?
- How to update one document in MongoDB?
- How to update many documents in MongoDB?
- How to use MongoDB queue?
- How to create a many to many relation in MongoDB?
- How to insert new document into MongoDB?
- How to use hint in MongoDB?
- How to work with time series data in MongoDB?
- How to use unwind in MongoDB?
See more codes...