خطوط تجميع البيانات والاستعلامات المعقدة
تشغيل خطوط التصفية والتجميع والاحتساب بكفاءة لدعم نقاط نهاية تحليلية.
خطوط تجميع البيانات والاستعلامات المعقدة درس مجاني في FastAPI Backend Development Bootcamp على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في FastAPI Backend Development Bootcamp، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Why Aggregation Pipelines?
Simple find queries return documents as-is. But analytics endpoints often need grouped, computed, and reshaped data: total revenue per month, average rating per product, top 10 active users.
MongoDB's aggregation pipeline runs this work inside the database, so you ship only the final result over the wire instead of pulling thousands of documents into Python and looping.
- Pipeline = an ordered list of stages
- Each stage takes a stream of documents in and emits documents out
- Beanie exposes it through
Document.aggregate(pipeline)
Our Beanie Models
Throughout this lesson we use an Order document. Each order has a customer, a status, a total amount, and a created timestamp. We'll build analytics endpoints on top of it.
Beanie documents subclass beanie.Document, which is itself a Pydantic model bound to a MongoDB collection.
from datetime import datetime
from beanie import Document
from pydantic import Field
class Order(Document):
customer_id: str
status: str # "paid", "pending", "cancelled"
total: float
created_at: datetime = Field(default_factory=datetime.utcnow)
class Settings:
name = "orders"The $match Stage
$match filters documents, exactly like a find query. Place it as early as possible so later stages process fewer documents and any indexes can be used.
This pipeline keeps only paid orders. Beanie's aggregate takes a plain list of dicts and runs it against the collection.
pipeline = [
{"$match": {"status": "paid"}}
]
paid_orders = await Order.aggregate(pipeline).to_list()The $group Stage
$group is the heart of analytics. It buckets documents by an _id expression and computes accumulators over each bucket.
$sum— total of a field (or count with$sum: 1)$avg,$min,$max$push/$addToSet— collect values into an array
Here we compute total revenue and order count per customer.
pipeline = [
{"$match": {"status": "paid"}},
{"$group": {
"_id": "$customer_id",
"revenue": {"$sum": "$total"},
"order_count": {"$sum": 1},
}},
]
rows = await Order.aggregate(pipeline).to_list()
# [{"_id": "c1", "revenue": 240.0, "order_count": 3}, ...]Field Paths vs Literals
Inside aggregation expressions, a string starting with $ is a field path (read the value of that field). A plain string is a literal.
"$total"→ the value of thetotalfield"total"→ the literal string "total"{"$sum": 1}→ add the literal1for every document = a count
Mixing these up is the #1 beginner mistake. $sum: "$total" sums amounts; $sum: 1 counts rows.
Sorting and Limiting Results
Add $sort and $limit after grouping to build a leaderboard. Sort uses 1 for ascending and -1 for descending.
This returns the top 5 customers by revenue — a classic analytics endpoint payload.
pipeline = [
{"$match": {"status": "paid"}},
{"$group": {
"_id": "$customer_id",
"revenue": {"$sum": "$total"},
}},
{"$sort": {"revenue": -1}},
{"$limit": 5},
]
top_customers = await Order.aggregate(pipeline).to_list()Reshaping with $project
$project chooses which fields to keep and lets you rename or compute new ones. After a $group the bucket key lives in _id, which is rarely the name your API consumers expect.
Here we rename _id to customer_id and drop the default _id from the output.
pipeline = [
{"$group": {
"_id": "$customer_id",
"revenue": {"$sum": "$total"},
}},
{"$project": {
"_id": 0,
"customer_id": "$_id",
"revenue": 1,
}},
]Mapping Results to a Pydantic Model
Aggregation returns raw dicts, not Order documents (the shape changed). Pass a projection_model so Beanie validates each row into a typed Pydantic model — perfect for a FastAPI response_model.
from pydantic import BaseModel
class CustomerRevenue(BaseModel):
customer_id: str
revenue: float
pipeline = [
{"$group": {"_id": "$customer_id", "revenue": {"$sum": "$total"}}},
{"$project": {"_id": 0, "customer_id": "$_id", "revenue": 1}},
{"$sort": {"revenue": -1}},
]
results = await Order.aggregate(
pipeline, projection_model=CustomerRevenue
).to_list() # List[CustomerRevenue]Grouping by Date with $dateToString
For time-series analytics, group by a formatted date. $dateToString turns a timestamp into a string bucket like "2026-06" for monthly revenue.
The result is ideal for charting endpoints: one row per month, sorted chronologically.
pipeline = [
{"$match": {"status": "paid"}},
{"$group": {
"_id": {"$dateToString": {
"format": "%Y-%m", "date": "$created_at"
}},
"revenue": {"$sum": "$total"},
}},
{"$sort": {"_id": 1}},
]
monthly = await Order.aggregate(pipeline).to_list()Wiring It Into a FastAPI Endpoint
Put the pipeline behind an async route. Because the aggregation runs in MongoDB, the handler stays tiny and fast even over millions of orders.
Using projection_model as the response_model gives you automatic validation and OpenAPI docs.
from fastapi import APIRouter
router = APIRouter()
@router.get("/analytics/top-customers", response_model=list[CustomerRevenue])
async def top_customers(limit: int = 5):
pipeline = [
{"$match": {"status": "paid"}},
{"$group": {"_id": "$customer_id", "revenue": {"$sum": "$total"}}},
{"$project": {"_id": 0, "customer_id": "$_id", "revenue": 1}},
{"$sort": {"revenue": -1}},
{"$limit": limit},
]
return await Order.aggregate(pipeline, projection_model=CustomerRevenue).to_list()Modeling a Pipeline in Pure Python
The pipeline pattern — match, group, sum — is just data transformation. Here is the same logic in plain Python so you can see what MongoDB does internally: filter, bucket by key, accumulate a sum.
In production MongoDB does this far faster and with indexes, but understanding the shape helps you write correct stages.
orders = [
{"customer_id": "c1", "status": "paid", "total": 100.0},
{"customer_id": "c2", "status": "paid", "total": 40.0},
{"customer_id": "c1", "status": "paid", "total": 60.0},
{"customer_id": "c2", "status": "pending", "total": 999.0},
]
revenue = {}
for o in orders:
if o["status"] != "paid": # $match
continue
revenue[o["customer_id"]] = revenue.get(o["customer_id"], 0) + o["total"] # $group + $sum
top = sorted(revenue.items(), key=lambda kv: kv[1], reverse=True) # $sort
for customer_id, total in top:
print(f"{customer_id}: {total}")Quick Check
You want total revenue per customer, counting only paid orders. Which pipeline is correct?
Recap
You can now build analytics-style endpoints with Beanie aggregation pipelines:
- $match early to filter and use indexes
- $group with accumulators (
$sum,$avg,$sum: 1for counts) - Remember field paths need a leading
$; plain strings are literals - $sort + $limit for leaderboards, $project to reshape and rename
_id - $dateToString for time-series buckets
- Pass
projection_modelto map raw rows into typed Pydantic models for clean FastAPIresponse_modeloutput
The pipeline runs inside MongoDB, keeping your handlers small and your endpoints fast.
الأسئلة الشائعة
هل درس «خطوط تجميع البيانات والاستعلامات المعقدة» مجاني؟
نعم — نص درس «خطوط تجميع البيانات والاستعلامات المعقدة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة FastAPI Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.
ماذا ستتعلم في «خطوط تجميع البيانات والاستعلامات المعقدة»؟
تشغيل خطوط التصفية والتجميع والاحتساب بكفاءة لدعم نقاط نهاية تحليلية. تتمرن على FastAPI Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ FastAPI Backend Development Bootcamp؟
لا تُشترط خبرة سابقة. FastAPI Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.
كم من الوقت يستغرق درس «خطوط تجميع البيانات والاستعلامات المعقدة»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس FastAPI Backend Development Bootcamp هذا؟
نعم. كل درس في FastAPI Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- الوصول غير المتزامن إلى MongoDB باستخدام Motor
- نمذجة المستندات باستخدام Beanie ODM
- خطوط تجميع البيانات والاستعلامات المعقدة
- تطور المخطط وترحيلات المستندات