Deleting & Aggregation
Remove documents, and get a first taste of aggregation for reports and summaries.
What you will learn
- Delete one and many documents
- Understand the aggregation pipeline
- Group and count data
Deleting
Deleting is the D in CRUD — it removes documents for good. Just like reading and updating, you pass a filter that decides which documents go. deleteOne(...) removes only the first match; deleteMany(...) removes every document that matches.
db.users.deleteOne({ name: "Ravi" }) // remove the first match
db.users.deleteMany({ active: false }) // remove all matchesThe first line finds the first user named Ravi and removes that one document. The second line finds every user whose active field is false and removes them all at once. The filter works exactly like the one in find — if it matches nothing, nothing is deleted.
Note: Output:
{ acknowledged: true, deletedCount: 1 }
deletedCount tells you how many documents were removed. For deleteMany it could be 0, 1, or many depending on how many matched the filter.
- Write a filter that selects only the documents you really want gone.
- Choose
deleteOne(just the first match) ordeleteMany(all matches). - MongoDB removes those documents permanently — there is no undo.
- It returns
deletedCountso you can confirm how many were removed.
Watch out: Be careful: deleteMany({}) with an empty filter deletes every document in the collection. Always double-check your filter before deleting.
Aggregation — summaries & reports
The aggregation pipeline processes documents through stages ($match, $group, $sort) to produce summaries — totals, averages, counts.
// Count users per city
db.users.aggregate([
{ $group: { _id: "$city", total: { $sum: 1 } } },
{ $sort: { total: -1 } }
])Think of the array as a conveyor belt of stages — documents flow through each one in order. The $group stage buckets users by city (the "$city" with a dollar sign means “the value of the city field”) and $sum: 1 adds 1 for each user in a bucket, giving a count. The $sort stage then orders those city totals from highest to lowest.
Note: Output: [ { _id: 'Bengaluru', total: 5 }, { _id: 'Mumbai', total: 3 }, { _id: 'Delhi', total: 2 } ] Each row is one city and how many users live there, biggest first. That is a ready-made report — no manual counting needed.
Tip: Aggregation is powerful for dashboards and analytics (sales per month, average rating per product). You can learn it deeply later — for now, know it exists and what it is for.
Q. What does the aggregation pipeline do?
✍️ Practice
- Delete one document, then delete all documents matching a condition.
- Use aggregation to count documents grouped by a field.
🏠 Homework
- Write an aggregation that finds the average price of products per category.