Skip to content

Aggregations

You can perform aggregation queries through bunnet as well. For example, to calculate the average:

# With a search:
avg_price = Product.find(
    Product.category.name == "Chocolate"
).avg(Product.price)

# Over the whole collection:
avg_price = Product.avg(Product.price)

A full list of available methods can be found here.

You can also use the native PyMongo syntax by calling the aggregate method. However, as Bunnet will not know what output to expect, you will have to supply a projection model yourself. If you do not supply a projection model, then a dictionary will be returned.

class OutputItem(BaseModel):
    id: str = Field(None, alias="_id")
    total: float


result = Product.find(
    Product.category.name == "Chocolate").aggregate(
    [{"$group": {"_id": "$category.name", "total": {"$avg": "$price"}}}],
    projection_model=OutputItem
).to_list()