how attribute does mongodb uses to group by ?
do they use only the "_id" or the ( "_id" AND "Total departments")
I am slightly confused because "_id" and "Total Departments" are in the same curly bracket $group
db.department.aggregate([
{
$group: {
"_id": {
"totalNumOfStaff": "$totalNumOfStaff",
"budget": "$budget"
},
"Total departments": {
$sum: "$budget"
}
}
}
]).pretty()
2
Answers
In your provided code sample, you are grouping by a composite key
{totalNumOfStaff, budget}
, which comes from 2 sources:totalNumOfStaff
andbudget
respectively. They are combined as the group key_id
.For
Total departments
, it is actually the aggregation depending on the group key_id
or{totalNumOfStaff, budget}
. You are doing$sum
by every unique combination of the group key{totalNumOfStaff, budget}
.MongoDB can compare objects also
Each document that is about to be grouped will get a grouping key, that
its that document
{"totalNumOfStaff": "$totalNumOfStaff","budget": "$budget"}
Based on the comparison algorithm (comparing the field names and values in order, see the link), it will decide to which group it belongs or create a new group for it.
In the above example same group is if same
totalNumOfStaff
AND samebudget
(order matters) and for each group sums the budget.