Databases python Intermediate

MongoDB Aggregation Pipeline

Count, group and sort documents using PyMongo aggregation pipeline.

python
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017")
db = client.myapp

pipeline = [
    {"$match":   {"is_published": True}},
    {"$group":   {"_id": "$category", "total": {"$sum": 1}, "avg_views": {"$avg": "$views"}}},
    {"$sort":    {"total": -1}},
    {"$project": {"category": "$_id", "total": 1, "avg_views": {"$round": ["$avg_views", 1]}, "_id": 0}},
]

results = list(db.modules.aggregate(pipeline))
for r in results:
    print(r)

Prerequisites

  • pymongo >= 4
  • MongoDB >= 6

Pro Tips

  • → Add {"$limit": 100} early in the pipeline to reduce processing.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
python
Level
Intermediate
Read time
4 min
Published
May 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.