Master MongoDB aggregation pipelines through hands-on practice with real-world schemas
A focused learning environment designed to help developers practice MongoDB aggregation pipelines using three interconnected collections: Users, Books, and Authors. Perfect for beginners to advanced developers who want to master complex aggregation operations.
$match- Filter documents based on conditions$project- Select and transform fields$group- Group documents and perform calculations$sort- Order your results$limit/$skip- Implement pagination$lookup- Join collections (SQL-like joins)$unwind- Deconstruct arrays$addFields- Add computed fields$facet- Multiple parallel pipelines
- Complex multi-stage pipelines
- Nested object manipulation
- Array operations and transformations
- Conditional expressions with
$cond,$switch - Date operations and grouping
- Text search and regex patterns
- Performance optimization techniques
{
"_id": ObjectId("..."),
"name": "John Doe",
"email": "john@example.com",
"isActive": true,
"age": 28,
"city": "New York",
"registrationDate": ISODate("2023-01-15"),
"preferences": {
"notifications": true,
"theme": "dark"
},
"tags": ["premium", "verified"]
}{
"_id": 1,
"title": "The Great Gatsby",
"author_id": 100,
"genre": "Classic",
"publishedYear": 1925,
"pages": 180,
"rating": 4.5,
"price": 12.99,
"inStock": true,
"reviews": [
{ "user": "alice", "rating": 5, "comment": "Masterpiece!" },
{ "user": "bob", "rating": 4, "comment": "Great read" }
]
}{
"_id": 100,
"name": "F. Scott Fitzgerald",
"birth_year": 1896,
"death_year": 1940,
"nationality": "American",
"genres": ["Classic", "Fiction", "Drama"],
"awards": ["Pulitzer Prize"],
"biography": "American novelist and short story writer..."
}git clone https://github.com/BuddhadebKoner/mongodb-aggregation-pipeline.git
cd mongodb-aggregation-pipeline
# Setup backend
cd server
npm install
cp .env.example .env
# Edit .env with your MongoDB connection string
# Setup frontend (optional - for visual interface)
cd ../frontend
npm install# Start backend server
cd server && npm run dev
# Start frontend (optional)
cd frontend && npm run devVisit http://localhost:5173 and use the Data Loader tab to populate your database with sample data, or use MongoDB Compass/CLI.
db.users.aggregate([
{ $match: { isActive: true } },
{ $project: { name: 1, email: 1, city: 1 } }
])db.books.aggregate([
{ $match: { genre: "Fiction" } },
{ $sort: { rating: -1 } },
{ $limit: 5 }
])db.users.aggregate([
{ $group: {
_id: "$city",
userCount: { $sum: 1 },
avgAge: { $avg: "$age" }
}},
{ $sort: { userCount: -1 } }
])db.books.aggregate([
{ $lookup: {
from: "authors",
localField: "author_id",
foreignField: "_id",
as: "authorInfo"
}},
{ $unwind: "$authorInfo" },
{ $project: {
title: 1,
"authorInfo.name": 1,
"authorInfo.nationality": 1,
rating: 1
}}
])db.books.aggregate([
// Join with authors
{ $lookup: {
from: "authors",
localField: "author_id",
foreignField: "_id",
as: "author"
}},
{ $unwind: "$author" },
// Add computed fields
{ $addFields: {
decade: { $subtract: [
"$publishedYear",
{ $mod: ["$publishedYear", 10] }
]},
reviewCount: { $size: "$reviews" },
avgReviewRating: { $avg: "$reviews.rating" }
}},
// Group by decade and author nationality
{ $group: {
_id: {
decade: "$decade",
nationality: "$author.nationality"
},
bookCount: { $sum: 1 },
avgRating: { $avg: "$rating" },
totalPages: { $sum: "$pages" },
authors: { $addToSet: "$author.name" }
}},
// Sort and format results
{ $sort: { "_id.decade": 1 } },
{ $project: {
decade: "$_id.decade",
nationality: "$_id.nationality",
bookCount: 1,
avgRating: { $round: ["$avgRating", 2] },
totalPages: 1,
uniqueAuthors: { $size: "$authors" },
_id: 0
}}
])db.books.aggregate([
{ $facet: {
// Books by rating ranges
"byRating": [
{ $bucket: {
groupBy: "$rating",
boundaries: [0, 2, 3, 4, 5],
default: "Other",
output: { count: { $sum: 1 } }
}}
],
// Top genres
"topGenres": [
{ $group: { _id: "$genre", count: { $sum: 1 } }},
{ $sort: { count: -1 } },
{ $limit: 5 }
],
// Publication timeline
"timeline": [
{ $group: {
_id: { $subtract: [ "$publishedYear", { $mod: ["$publishedYear", 10] } ] },
books: { $sum: 1 }
}},
{ $sort: { "_id": 1 } }
]
}}
])POST /load-users- Load sample user dataPOST /load-books- Load sample book dataPOST /load-authors- Load sample author dataDELETE /clear-all- Reset all collections
GET /questions/active-users- Get active users with aggregation- Add more endpoints by contributing!
- Master
$match,$project,$sort,$limit - Practice basic filtering and field selection
- Work with simple grouping operations
- Learn
$lookupfor joining collections - Practice
$unwindfor array operations - Combine books with author information
- Complex
$groupoperations with multiple fields - Use
$bucketand$bucketAutofor data distribution - Calculate statistics and aggregations
- Multi-stage pipelines for real scenarios
- Performance optimization with indexes
$facetfor parallel pipeline execution
Create a pipeline that shows:
- Users per city
- Average age by city
- Most active registration months
Build a pipeline that:
- Finds books similar to a given book
- Groups by genre and rating
- Includes author information
Develop analytics showing:
- Revenue by genre and year
- Top-performing authors
- Seasonal reading patterns
Implement a system that:
- Searches books by title/author
- Filters by multiple criteria
- Supports pagination and sorting
- Pipeline Design: Structure complex multi-stage operations
- Performance: Optimize queries with proper indexing
- Data Modeling: Understand document relationships
- Aggregation Operators: Master 50+ aggregation operators
- Real-world Patterns: Apply aggregation in production scenarios
Add new aggregation challenges:
- Create Controller Function (
server/controllers/aggregationController.js):
export const yourNewQuestion = async (req, res) => {
try {
const pipeline = [
// Your aggregation pipeline here
];
const result = await YourModel.aggregate(pipeline);
res.json({
success: true,
totalResults: result.length,
data: result,
pipeline: pipeline,
explanation: {
stages: [
{ stage: "$match", purpose: "Filter documents" },
// ... more explanations
]
}
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};- Add Route (
server/server.js):
app.get('/questions/your-new-question', yourNewQuestion);- Update Frontend (optional) - Add endpoint to the practice interface
- Real Schemas: Practice with realistic, interconnected data
- Progressive Learning: Start simple, build complexity gradually
- Visual Feedback: See results immediately in table/JSON format
- Production Ready: Learn patterns used in real applications
- Community Driven: Contribute and learn from others
- MongoDB Aggregation Documentation
- Aggregation Pipeline Quick Reference
- MongoDB University - Free courses
π Start practicing now and become a MongoDB aggregation expert!
This environment provides everything you need to master MongoDB aggregation pipelines through hands-on practice with realistic data structures.