VOOZH about

URL: https://www.geeksforgeeks.org/python/python-mongodb-group-aggregation/

⇱ Python MongoDB - $group (aggregation) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python MongoDB - $group (aggregation)

Last Updated : 15 Jul, 2025

In PyMongo, the aggregate() method processes data through a pipeline of stages to produce aggregated results. One key stage is $group, which groups documents based on a specified identifier like a field name and applies accumulator operations e.g., $sum, $avg, $max. It then outputs a new set of documents representing the grouped and processed data.

Syntax

{
$group: {
_id: <grouping field>,
<newField>: { <accumulator>: <expression> }
}
}

Parameters:

  • _id: The field to group the documents by (e.g., group by "product name" or "category").
  • <newField>: The result field where you store the output (like total, average, etc.).
  • <accumulator>: The operation to perform on each group.
  • <expression>: The value to apply the operation on (e.g., the "amount" field).

Here is our sample data.

Output

Data inserted.
👁 Output
Data inserted

Explanation:

  • MongoClient() connects to the local server and selects grpDB.sales.
  • insert_many(data) loads sample orders into the sales collection.
  • delete_many({}) clears previous data to avoid duplicates.

Examples

Example 1: Average amount per user

Output

👁 Output
User-wise average

Explanation:

  • $group groups documents by user.
  • $avg calculates average amount spent by each user.

Example 2: Total amount per product

Output

👁 Output
Product-wise total

Explanation:

  • $group organizes documents by product.
  • $sum computes the total sales amount for each product.

Example 3: Max amount spent per user

Output

👁 Output
User-wise max spend

Explanation:

  • $group groups orders by user.
  • $max finds the highest amount spent by each user in a single transaction.

Related Articles

Comment
Article Tags: