The Brief
You're building the backend for FreshBasket, a grocery delivery platform. Your mission: create a production-ready product catalog with:
- CRUD operations — Create, read, update, and delete products.
- Full-text search — Let customers find "avocado" or "organic honey" instantly.
- Smart filtering — By category, price range, ratings, and stock levels.
- Analytics pipelines — Revenue by category, top suppliers, low-stock alerts, and inventory value metrics.
- Batch operations — Seed 100+ products and adjust prices at scale.
By the end, you'll have a fully functional MongoDB backend that powers a real grocery app. Let's build it.
Setup & Indexes
Before writing code, you need to connect to MongoDB and create indexes for performance. Text indexes enable full-text search; other indexes speed up common queries.
Q0: Connect and Create Indexes
What these indexes do:
create_index([('name', 'text'), ...])— Text index for full-text search across name, category, and tags.create_index([('category', 1)])— Speed up category filters.create_index([('supplier.name', 1)])— Speed up supplier lookups.create_index([('avg_rating', -1)])— Speed up sorting by rating (descending).create_index([('stock', 1)])— Speed up stock availability checks.
CRUD Operations
Q1: Create Product
Q2: Get Product by ID
Stock: 75
Rating: 4.6 (0 reviews)
Q3: Update Stock (After Purchase)
Q4: Add Tag (Without Duplicates)
Q5: Add Review & Update Rating
Q6: Delete Product
Search & Filter
Q7: Full-Text Search
Q8: Filter by Category
Q9: Affordable Products (Price Range)
Q10: Top Rated Products
Cabbage 1pc - 4.9⭐
Cheddar Cheese 200g - 4.9⭐
Analytics Pipelines
MongoDB aggregation pipelines let you analyze data at scale. Use $addFields, $group, and $sort to unlock insights.
Q11: Revenue by Category (Inventory Value)
Grains: KES 2311165 (10 products)
Dairy: KES 2094267 (10 products)
Q12: Top Suppliers (by Inventory Value)
Coast Fisheries: KES 2007969 (Mombasa)
Thika Fresh: KES 1867087 (Thika)
Q13: Recently Added Products
Q14: Low Stock Alert
Spaghetti 500g: 8 units
Potato Crisps 200g: 8 units
Croissants 4-pack: 8 units
Q15: Category Summary (Overview)
Vegetables: 10 products, KES 163-2307, Rating: 4.14
Spices: 10 products, KES 525-2383, Rating: 4.08
Batch Operations
Q16: Seed Catalog (Bulk Insert)
Q17: Bulk Price Adjustment
Running the Demo
Here's a complete main function that runs all operations together:
1. Setting up indexes...
2. Creating a new product...
Created: 69e0a6a14d75051788b18efa
[... full output continues ...]
Challenge
Add an endpoint that returns products sorted by inventory value (price × stock) with pagination.
Requirements:
- Calculate inventory value = price × stock for each product.
- Sort by inventory value descending (highest value first).
- Support pagination with
pageandlimitparameters. - Return total count, current page, and products.
Use an aggregation pipeline with $addFields to compute inventory_value, then $sort, $skip, and $limit for pagination: