Home > OS >  how does mongo db group by using aggregate?
how does mongo db group by using aggregate?

Time:06-06

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()

CodePudding user response:

In your provided code sample, you are grouping by a composite key {totalNumOfStaff, budget}, which comes from 2 sources: totalNumOfStaff and budget 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}.

CodePudding user response:

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 same budget(order matters) and for each group sums the budget.

  • Related