Relational tables expect predictable rows and columns. However, modern telemetry, device logs, social posts, and dynamic product catalogs often arrive as semi-structured documents with arbitrary nesting. MongoDB and NoSQL provide the dynamic storage engine to capture and aggregate this data.
| Relational SQL Clause | MongoDB Pipeline Stage | Operational Behavior |
|---|---|---|
WHERE |
$match |
Filters documents to allow only matching items to proceed. |
SELECT (Columns) |
$project |
Reshapes documents, computes new fields, or suppresses attributes. |
GROUP BY & Aggregates |
$group |
Groups documents by specified accumulator keys ($sum, $avg). |
ORDER BY |
$sort |
Orders incoming stream in ascending (+1) or descending (-1) order. |
LIMIT |
$limit |
Restricts total document throughput to specified count. |
| (No direct SQL equivalent) | $unwind |
Explodes array elements into separate individual records. |
import pymongo
import pandas as pd
# Connect to local or cloud MongoDB cluster
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["ecommerce_db"]
orders_col = db["orders"]
# Aggregation pipeline: Average order value by customer country in 2026
pipeline = [
{"$match": {"status": "DELIVERED", "year": 2026}},
{"$unwind": "$items"}, # Explode array of purchased products
{
"$group": {
"_id": "$shipping_address.country",
"total_items_sold": {"$sum": "$items.quantity"},
"total_revenue": {"$sum": {"$multiply": ["$items.quantity", "$items.price"]}},
"order_count": {"$addToSet": "$_id"} # Distinct count of order IDs
}
},
{
"$project": {
"country": "$_id",
"total_revenue": 1,
"total_items_sold": 1,
"total_orders": {"$size": "$order_count"},
"avg_order_value": {"$round": [{"$divide": ["$total_revenue", {"$size": "$order_count"}]}, 2]}
}
},
{"$sort": {"total_revenue": -1}},
{"$limit": 10}
]
cursor = orders_col.aggregate(pipeline)
df_mongo = pd.DataFrame(list(cursor))
print(df_mongo[['country', 'total_revenue', 'total_orders', 'avg_order_value']])
State the CAP Theorem (Consistency, Availability, Partition Tolerance) and explain where MongoDB sits on the spectrum. (Answer: MongoDB is classified primarily as a CP system — prioritizing Consistency and Partition Tolerance over Availability during network splits).
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
Handle dynamic and nested semi-structured data formats seamlessly.
Store unstructured text, logs, and scraped HTML in document collections.
Combine document stores with dense vector embeddings for search.
Master differences between RDBMS and NoSQL for university exams.