1.
Total Revenue from Sales
Query:
db.sales.aggregate([
{ $group: { _id: null, totalRevenue: { $sum: "$amount" } } }
]);
Reference: Page 151, 438
2. Top 5 Best-Selling Products
Query:
db.sales.aggregate([
{ $group: { _id: "$product_id", totalSold: { $sum: "$quantity" } } },
{ $sort: { totalSold: -1 } },
{ $limit: 5 }
]);
Reference: Pages 151-152, 438
3. Group Sales by Month
Query:
db.sales.aggregate([
{ $group: { _id: { $month: "$saleDate" }, monthlyRevenue: { $sum: "$amount" } } },
{ $sort: { "_id": 1 } }
]);
Reference: Pages 437-438
4. Average Sale Price per Product
Query:
db.sales.aggregate([
{ $group: { _id: "$product_id", avgPrice: { $avg: "$price" } } }
]);
Reference: Page 438
5. Restaurants with >3 Grade Surveys
Query:
db.restaurants.aggregate([
{ $project: { name: 1, numGrades: { $size: "$grades" } } },
{ $match: { numGrades: { $gt: 3 } } },
{ $project: { name: 1, numGrades: 1 } }
]);
Reference: Pages 140, 151-153
6. Electronics Products < $500
Query:
db.products.find({ category: "Electronics", price: { $lt: 500 } });
Reference: Page 140
7. Library Book Stats
a. Total Books:
db.books.countDocuments();
b. Borrowed by Member:
db.books.aggregate([
{ $match: { borrower_id: { $exists: true } } },
{ $group: { _id: "$borrower_id", borrowedCount: { $sum: 1 } } }
]);
c. Active Members:
db.members.countDocuments({ isActive: true });
d. Books by Category:
db.books.aggregate([
{ $match: { borrower_id: { $exists: true } } },
{ $group: { _id: "$category", count: { $sum: 1 } } }
]);
Reference: Pages 144-150 (CRUD), 151-153 (Aggregation)
8. Recipe-Sharing System
Schema:
db.recipes.insertMany([
{ title: 'Pasta', ingredients: ['noodles', 'sauce'], user: 'alice', bookmarks: [] },
{ title: 'Pizza', ingredients: ['dough', 'cheese'], user: 'bob', bookmarks: [] },
{ title: 'Salad', ingredients: ['lettuce', 'tomato'], user: 'carol', bookmarks: [] },
{ title: 'Soup', ingredients: ['water', 'vegetables'], user: 'dave', bookmarks: [] },
{ title: 'Cake', ingredients: ['flour', 'sugar'], user: 'eve', bookmarks: [] }
]);
Bookmark Recipe:
db.recipes.updateOne({ title: 'Pasta' }, { $push: { bookmarks: 'user123' } });
Reference: Pages 144-146 (Insert & Update examples)
9. Student Document Sharing
Schema (users, documents):
Create User:
db.users.insertOne({ name: 'John Doe', role: 'student' });
Update User Role:
db.users.updateOne({ name: 'John Doe' }, { $set: { role: 'teacher' } });
Insert Document:
db.documents.insertOne({ title: 'Notes', user_id: ObjectId('...'), rating: 5 });
Update Rating:
db.documents.updateOne({ title: 'Notes' }, { $set: { rating: 4 } });
Find 5-Star Documents:
db.documents.find({ user_id: ObjectId('...'), rating: 5 });
Reference: Pages 144-150
10. Hospital Management Schema
Collections: patients, doctors, appointments
Add Patient:
db.patients.insertOne({ name: 'Jane Doe', age: 30 });
List Doctors with Schedules:
db.doctors.find({}, { name: 1, schedule: 1 });
Find Appointments by Patient ID:
db.appointments.find({ patient_id: ObjectId('...') });
Find Appointments by Doctor ID:
db.appointments.find({ doctor_id: ObjectId('...') });
Reference: Pages 138-141 (Document structure), 144-150 (CRUD)
11. Create Index on Category Field
Create Index:
db.products.createIndex({ category: 1 });
Other Strategies:
- Compound Index: db.products.createIndex({ category: 1, price: -1 })
- Text Index for search: db.products.createIndex({ name: "text", description: "text" })
- Covered Queries: Ensure index covers all queried fields
- Analyze with explain(): db.products.find({ category: 'Books' }).explain()
Reference: Pages 140-141, 153
12. Ensure Unique product_id
Use Unique Index:
db.products.createIndex({ product_id: 1 }, { unique: true });
This enforces uniqueness at the database level.
Reference: Page 141
13. Insert Nested Room in User's House
Assuming structure: user -> house -> rooms
Update Query:
db.users.updateOne(
{ _id: ObjectId("user_id") },
{ $push: { "house.rooms": { name: "Room 44", size: "50" } } }
);
Reference: Pages 138-139 (Nested Documents)
14. MongoDB Global Connection After Server Restart
When the MongoDB connection is stored globally (e.g., during app startup), if the server is restarted,
the existing connection object is lost in memory. Thus, it must be re-established during server reinitialization.
Best practice: Reconnect on server start using a connection handler.
Reference: Page 153
15. Removing 'exact' from <Redirect />
Without 'exact', <Redirect /> may trigger on partial URL matches, causing unintended redirection.
Routing can still work, but efficiency and correctness depend on careful route order.
Reference: Page 311
16. React Router Setup for Pages
Example Setup:
<Switch>
<Route path='/' exact component={Home} />
<Route path='/products' exact component={ProductList} />
<Route path='/products/:id' component={ProductDetails} />
<Route path='/cart' component={Cart} />
</Switch>
Reference: Pages 303-305
17. Nested Route for Product Details
Inside ProductList Component:
<Route path='/products/:id' component={ProductDetails} />
Reference: Page 311
18. Handle 404 Errors in React Router
Use a fallback Route:
<Switch>
...existing routes...
<Route component={NotFound} />
</Switch>
Reference: Page 317
19. Protected Routes for Authenticated Users
Custom ProtectedRoute Component:
function ProtectedRoute({ component: Component, ...rest }) {
return <Route {...rest} render={(props) => (
isAuthenticated ? <Component {...props} /> : <Redirect to='/login' />
)} />;
}
Reference: Conceptually related to Pages 311-317; auth logic must be implemented manually
20. React Filter Component for Job Listings
Example Filter Component:
function JobFilter({ onFilter }) {
const [location, setLocation] = useState('');
const [jobType, setJobType] = useState('');
const [salary, setSalary] = useState('');
const applyFilters = () => onFilter({ location, jobType, salary });
return (
<form onSubmit={e => { e.preventDefault(); applyFilters(); }}>
<input type='text' placeholder='Location' onChange={e => setLocation(e.target.value)} />
<input type='text' placeholder='Job Type' onChange={e => setJobType(e.target.value)} />
<input type='number' placeholder='Salary' onChange={e => setSalary(e.target.value)} />
<button type='submit'>Apply</button>
</form>
);
}
Reference: Pages 241-249
21. Handle Form Submission and Update Listings
Use State and Prop Callback:
Parent holds job listings and updates them based on filter result.
Pass down onFilter callback to filter component.
Reference: Page 244
22. Validate Salary Input Client Side
Use input type='number' + min attribute:
<input type='number' min='0' onChange={...} />
Add extra check in handler:
if (salary < 0) setError('Invalid salary');
Reference: Page 249
23. Manage Filter Criteria with State
Maintain state for filters (location, type, salary) using useState().
Filter job list using array filter method on state change.
Reference: Pages 241-245
24. Bootstrap Login Form
Example with React-Bootstrap:
<Form>
<Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control type='email' placeholder='Enter email' />
</Form.Group>
<Form.Group>
<Form.Label>Password</Form.Label>
<Form.Control type='password' placeholder='Password' />
</Form.Group>
<Form.Check type='checkbox' label='Remember me' />
<Button type='submit'>Login</Button>
</Form>
Reference: Pages 370-372
25. Benefits of SSR for News Websites
- Faster initial page load
- Improved SEO (search engines can crawl content)
- Better sharing preview (social media)
Reference: Page 390
26. SSR for React Component
Use renderToString from 'react-dom/server':
const html = renderToString(<App />);
res.send(`<!doctype html><div id='root'>${html}</div>`);
Reference: Pages 393-397
27. State Handling in SSR
- Fetch data server-side and embed in HTML
- Client reads from window.__INITIAL_DATA__
- Use hydrate instead of render on client
Reference: Pages 398-405
28. SSR Challenges & Solutions
- Duplicate logic between client/server => Use shared code
- Asynchronous data fetching => use promises or await
- State mismatch => hydrate properly
Reference: Pages 416-417
29. Express API to Update Task by task_id
app.put('/api/tasks/:id', async (req, res) => {
try {
const result = await Task.updateOne(
{ _id: req.params.id },
{ $set: req.body }
);
res.json(result);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
Reference: Page 213
30. Express API to Delete Task by task_id
app.delete('/api/tasks/:id', async (req, res) => {
try {
const result = await Task.deleteOne({ _id: req.params.id });
res.json(result);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
Reference: Page 213
31. Error Handling in Express API
- Use try/catch blocks around async operations
- Send standardized error responses
- Example:
app.get('/api/resource', async (req, res) => {
try {
const data = await fetchData();
res.json(data);
} catch (err) {
res.status(500).json({ error: 'Internal Server Error' });
}
});
Reference: Pages 207-209
32. Testing Express with Postman
- Start the Express server
- Open Postman, choose GET/POST/PUT/DELETE
- Enter endpoint URL (e.g., http://localhost:3000/api/tasks)
- Use the Body tab (JSON) for POST/PUT
- Check response and status code
Reference: Page 215