A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-mongodb-group-aggregation/ below:

Python MongoDB - $group (aggregation)

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:

Here is our sample data.

Python
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['grpDB']
col = db['sales']

data = [
    {"_id": 1, "user": "Amit", "product": "Pen", "amount": 5},
    {"_id": 2, "user": "Drew", "product": "Pencil", "amount": 3},
    {"_id": 3, "user": "Amit", "product": "Notebook", "amount": 15},
    {"_id": 4, "user": "Cody", "product": "Pen", "amount": 7},
    {"_id": 5, "user": "Drew", "product": "Notebook", "amount": 12},
    {"_id": 6, "user": "Cody", "product": "Eraser", "amount": 2},
    {"_id": 7, "user": "Amit", "product": "Pen", "amount": 10}
]
col.delete_many({})
col.insert_many(data)
print("Data inserted.")

Output

Data inserted.
Data inserted

Explanation:

Examples

Example 1: Average amount per user

Python
from pymongo import MongoClient

c = MongoClient("mongodb://localhost:27017/")
db = c['groupExampleDB']
collection = db['sales']

res = collection.aggregate([
    {
        "$group": {
            "_id": "$user",
            "average_amount": { "$avg": "$amount" }
        }
    }
])

for doc in res:
    print(doc)

Output

User-wise average

Explanation:

Example 2: Total amount per product

Python
from pymongo import MongoClient
c = MongoClient("mongodb://localhost:27017/")
db = c['grpDB']
col = db['sales']

res = col.aggregate([
    {
        "$group": {
            "_id": "$product",
            "total_amount": { "$sum": "$amount" }
        }
    }
])
for doc in res:
    print(doc)

Output

Product-wise total

Explanation:

Example 3: Max amount spent per user

Python
from pymongo import MongoClient

c = MongoClient("mongodb://localhost:27017/")
db = c['grpDB']
col = db['sales']

res = col.aggregate([
    {
        "$group": {
            "_id": "$user",
            "max_spent": { "$max": "$amount" }
        }
    }
])
for doc in res:
    print(doc)

Output

User-wise max spend

Explanation:

Related Articles



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4