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.
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.
Similar Modules
MySQL Replication Status Check
Script to check MySQL/MariaDB replication lag and alert if it exceeds threshold.
sql
·
Intermediate
DB Connection Pool Monitor
Query to check active connections, idle connections and pool usage in PostgreSQL.
sql
·
Intermediate
Cursor-based Pagination Query
Implement cursor-based (keyset) pagination in SQL — faster than OFFSET for large tables.
sql
·
Intermediate