Theory
From raw records to answers
FestConnect's organiser does not want to read every event document; they want ANSWERS: 'show me the 3 biggest events', 'how many people registered for each event', 'what is the total seat capacity'. These need more than a plain find: they need SORTING, LIMITING, and grouping.
This lesson finishes MongoDB with the tools that turn stored documents into insights: sort and limit to shape results, precise update operators like $inc, and the AGGREGATION pipeline, MongoDB's powerful equivalent of SQL's GROUP BY. This is where the database earns its keep for reporting.
Theory
Sort, limit, and precise updates
Shaping reads by chaining onto find:
.sort({ seats: -1 }): order results: -1 descending, 1 ascending.limit(2): return at most 2.skip(n): skip the first n (for paging)
So find().sort({ seats: -1 }).limit(3) gives the 3 biggest events.
Precise updates with operators beyond $set:
$inc: increment/decrement a number:{ $inc: { seats: -1 } }books one seat$push: add to an array;$pull: remove from an array;$unset: remove a field
These change exactly one aspect of a document without touching the rest, the safe alternative to whole-document replacement.
Practical
Sort + limit, $inc, and an aggregation
// Events: Garba 350, Coding 60, Webinar 500
// Top 2 events by seats (descending):
db.events.find({}, { name: 1, _id: 0 }).sort({ seats: -1 }).limit(2)
// -> { name: "Webinar" }, { name: "Garba Night" } (500, then 350)
// Book a seat: decrement with $inc
db.events.updateOne({ name: "Garba Night" }, { $inc: { seats: -1 } })
// Garba Night now has 349
// AGGREGATION: count registrations per event
db.registrations.aggregate([
{ $match: { paid: true } }, // stage 1: filter
{ $group: { _id: "$event", total: { $sum: 1 } } }, // stage 2: group + count
{ $sort: { total: -1 } } // stage 3: sort
])
// e.g. { _id: "Garba Night", total: 40 }, ...
This example runs in Gri-Learn on the web, where you can edit it and see the output.
Theory
The aggregation pipeline
Aggregation processes documents through an ordered SEQUENCE of STAGES, each transforming the stream that flows to the next, like a factory line. The common stages:
- $match: filter documents (like find)
- $group: group by a field and compute AGGREGATES:
$sum,$avg,$max, counts - $sort, $project, $limit: order, reshape, cap
The example above filters to paid registrations ($match), groups them by event and counts each group ($group with $sum: 1), then sorts by the count. The result: registrations per event, most popular first. This is MongoDB's answer to SQL's GROUP BY, and the ORDER of stages matters: each stage feeds the next.
Quiz
In db.events.find().sort({ seats: -1 }), what does the -1 do?
- Returns only 1 document
- Sorts the results by seats in DESCENDING order (largest first); 1 would be ascending
- Removes the seats field
- Deletes documents with negative seats
Show the answer
Sorts the results by seats in DESCENDING order (largest first); 1 would be ascending
In sort(), the value 1 means ASCENDING and -1 means DESCENDING, so sort({ seats: -1 }) orders events by seats from largest to smallest. Option A confuses sort with limit(1). Option C confuses it with projection (seats: 0 would exclude the field). Option D invents a delete operation. Remember the sort convention: 1 up, -1 down: it is a frequent exam and real-world detail (getting it backwards silently returns results in the wrong order). Combine sort with limit to get 'the top N': sort descending, then limit.
Think first
Why is aggregation a pipeline of stages?
Aggregation runs $match, then $group, then $sort as separate ordered stages. Why structure it this way rather than one big query, and does the order matter? Then tap.
Show the answer
The pipeline structure lets each stage do ONE transformation and pass its output to the next, like an assembly line: filter the documents ($match), then group and summarise what survived ($group), then order the summary ($sort). This makes complex data processing readable and composable: you build a big transformation from small, understandable steps. And ORDER absolutely matters: $match FIRST (before $group) filters early so you group fewer documents (efficient and correct); putting $sort before $group would sort the wrong thing. Reordering stages changes the result and the performance. Think of it as a factory line: raw documents in, each stage refines, the answer comes out the end. Design the stages in the order the data needs to flow.
Watch out
Operator and aggregation traps
Sort direction backwards: -1 is descending, 1 ascending; getting it wrong silently reorders results.
$inc vs $set for counters: use $inc to change a number relative to its current value (booking a seat); $set would need you to know the exact new value.
Aggregation stage order: $match before $group (filter early); order changes results.
Forgetting the $ on field names in $group: group by "$event" (with $), not "event".
Confusing find-chaining with aggregation: sort/limit chain onto find; $group only exists in aggregate().
Theory
Unit 1 complete: the modern data layer
FestConnect now has a full NoSQL data layer: documents in collections, complete CRUD, query and projection operators, result shaping, and aggregation for reporting. That is the DATA half of the modern web stack. Unit 2 builds the UI half with React: components, props, state, events, forms and hooks, so FestConnect gets a modern, reactive front-end sitting on this MongoDB back-end. From data to interface.
Summary
Key takeaways
- Shape reads by chaining: .sort({field: -1}) descending / 1 ascending, .limit(n) caps, .skip(n) pages.
- find().sort({seats:-1}).limit(3) gives the top 3 by seats.
- Update operators beyond $set: $inc (increment, e.g. book a seat), $push/$pull (array add/remove), $unset (remove field).
- Aggregation processes documents through ordered STAGES: $match (filter), $group (group + aggregate), $sort, $project, $limit.
- $group with accumulators ($sum, $avg, count) is MongoDB's GROUP BY; put $match before $group.
- Stage order matters: each stage feeds the next, like a factory line.
- Memory hook: sort -1 is down, $inc counts, aggregation is a pipeline of stages.