skip to content
Alvin Lucillo

MongoDB Compass aggregate function

/ 1 min read

💻 Tech

Just like in SQL, MongoDB, a document-based database can also perform data aggregation. The example query below uses $sum, which is similar to SQL’s SUM() function.

The example query below is equivalent to SQL’s SELECT SUM(salary) total_salary ... GROUP BY dept_id. _id value specifies the grouping key, which in this case is the dept_id field. It has the dollar character to signify that it’s a document field.

[
  {
    "$group": {
      "_id": "$dept_id",
      "total_salary": {
        "$sum": "$salary"
      }
    }
  }
]

If you want to incorporate multiple grouping key, you can make _id a composite key.

[
  {
    "$group": {
      "_id": {
        deptId: "$dept_id",
        type: "$type"
      },
      "total_salary": {
        "$sum": "$salary"
      }
    }
  }
]