Updating and Deleting Data in MongoDB
A Magical Eraser & Pencil Adventure - For Beginner to Expert Level
Imagine you have a super-smart notebook where you can change a drawing with a magic pencil or erase it with a magic eraser — without messing up the whole page! In MongoDB, updating means changing data, and deleting means removing it. This tutorial is a fun art class, super easy for beginners, but full of pro secrets for experts.
We’ll use:
- Our Hero Academy from before
- mongosh (command line)
- MongoDB Compass (click & edit)
- Real images
- Beginner → Expert tips
Let’s grab the pencil and eraser!
Table of Contents
- Part 1: Sample Data (Your Hero Notebook)
- Part 2: Updating Data: The Magic Pencil
- Part 3: Deleting Data: The Magic Eraser
- Part 4: Using Compass: Click to Edit & Delete
- Part 5: Pro Update Operators (Expert Level)
- Part 6: Mini Project: Hero Academy Management!
- Part 7: Safety First (Important Rules)
- Part 8: Pro Tips for All Levels
- Part 9: Cheat Sheet
- Part 10: Common Mistakes & Fixes
- When to Use updateMany vs bulkWrite
- Error Handling Examples
Part 1: Sample Data (Your Hero Notebook)
Run this in mongosh (or skip if you have data):
use heroAcademy
db.heroes.insertMany([
{ name: "Aarav", power: "Super Speed", level: 5, isActive: true, team: "Alpha" },
{ name: "Priya", power: "Invisibility", level: 7, isActive: true, team: "Alpha" },
{ name: "Rohan", power: "Fire Control", level: 4, isActive: false, team: "Beta" },
{ name: "Sanya", power: "Telekinesis", level: 6, isActive: true, team: "Beta" },
{ name: "Karan", power: "Ice Blast", level: 3, isActive: true, team: "Alpha" }
])
Part 2: Updating Data: The Magic Pencil
1. updateOne – Change One Hero
db.heroes.updateOne(
{ name: "Aarav" }, // Filter: Find Aarav
{ $set: { level: 6, isActive: true } } // Change: level → 6
)
Output:
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
Beginner Win: Aarav got promoted!
matchedCount: Found 1 hero
modifiedCount: Actually changed 1
updateOne → silent update. findOneAndUpdate → returns old/new doc.
2. updateMany - Change Many Heroes
db.heroes.updateMany(
{ team: "Alpha" }, // All Alpha team
{ $set: { uniform: "Blue" } } // Add uniform
)
Result: Aarav, Priya, Karan now have "uniform": "Blue"
3. $inc – Increase Numbers
db.heroes.updateOne(
{ name: "Priya" },
{ $inc: { level: 1 } }
)
→ Priya’s level: 7 → 8
Like: Giving +1 star for good work!
4. $push – Add to Array
db.heroes.updateOne(
{ name: "Sanya" },
{ $push: { skills: "mind control" } }
)
→ Sanya’s skills: ["lift", "fly"] → ["lift", "fly", "mind control"]
5. $pull – Remove from Array
db.heroes.updateOne(
{ name: "Sanya" },
{ $pull: { skills: "fly" } }
)
→ Removes "fly" from skills
6. replaceOne – Replace Entire Hero
db.heroes.replaceOne(
{ name: "Karan" },
{
name: "Karan",
power: "Ice Storm",
level: 5,
isActive: true,
team: "Alpha",
newPower: true
}
)
Warning: Replaces everything — old fields like skills are gone!
Part 3: Deleting Data: The Magic Eraser
In this part, you'll learn how to safely remove data from one document to the entire database.
1. deleteOne – Erase One Hero
db.heroes.deleteOne({ name: "Rohan" })
→ Rohan is gone!
2. deleteMany – Erase Many Heroes
db.heroes.deleteMany({ isActive: false })
→ All inactive heroes erased!
3. Delete Entire Collection
db.heroes.drop()
→ Whole heroes shelf gone!
4. Delete Entire Database
db.dropDatabase()
→ Whole heroAcademy toy box gone! Be careful!
Part 4: Using Compass: Click to Edit & Delete
Step 1: Open Compass → heroAcademy → heroes
Step 2: Edit with Click
Click on Priya’s row
Click pencil icon
Change level: 8 → 9
Click Update
Compass Edit
Step 3: Delete with Click
Hover over a hero
Click trash icon
Confirm Delete
Beginner Magic: No typing. Just click.
Part 5: Pro Update Operators (Expert Level)
| Operator | Use | Example |
|---|---|---|
| $set | Set a field | { $set: { team: "Gamma" } } |
| $unset | Remove a field | { $unset: { uniform: "" } } |
| $rename | Rename a field | { $rename: { level: "rank" } } |
| $push | Add to array | { $push: { skills: "laser" } } |
| $addToSet | Add only if not exists | { $addToSet: { skills: "fly" } } |
| $pop | Remove first/last from array | { $pop: { skills: 1 } } |
| $inc | Increase number | { $inc: { level: 2 } } |
Part 6: Mini Project: Hero Academy Management
Let’s run a real school!
1. Promote All Active Alpha Heroes
db.heroes.updateMany(
{ team: "Alpha", isActive: true },
{ $inc: { level: 1 }, $set: { badge: "Gold" } }
)
2. Add New Skill to Top Hero
db.heroes.updateOne(
{ level: { $gte: 8 } },
{ $push: { skills: "leadership" } }
)
3. Remove Inactive Heroes
db.heroes.deleteMany({ isActive: false })
4. Clean Up Old Uniforms
db.heroes.updateMany(
{},
{ $unset: { uniform: "" } }
)
Part 7: Safety First (Important Rules)
| Rule | Why It Matters |
|---|---|
| Always use filter | Prevent updating/deleting everything |
| Test with find() first | See what will change |
| Backup before drop() | No undo! |
| Use updateOne for single edits | Safer than updateMany |
Part 8: Pro Tips for All Levels
For Students & Beginners
- Use Compass to click and change
- Start with updateOne
- Make a "Pet Diary" – update pet age!
For Medium Learners
Use upsert (update or insert):
db.heroes.updateOne(
{ name: "New Hero" },
{ $set: { power: "Light" } },
{ upsert: true }
)
→ Creates if not found!
Return updated document:
db.heroes.findOneAndUpdate(
{ name: "Priya" },
{ $inc: { level: 1 } },
{ returnNewDocument: true }
)
For Experts
Use pipeline updates (MongoDB 4.2+):
db.heroes.updateOne(
{ name: "Sanya" },
[
{ $set: { level: { $add: ["$level", 1] } } },
{ $set: { status: { $cond: [ { $gte: ["$level", 10] }, "Master", "Hero" ] } } }
]
)
Atomic updates with transactions:
const session = db.getMongo().startSession()
session.startTransaction()
// ... updates
session.commitTransaction()
When to Use updateMany vs bulkWrite
Use updateMany when:
- You want to apply the same update to multiple documents.
- You only need one filter and one update definition.
- You don’t need per-document custom updates.
- You want a simple operation with minimal complexity.
db.heroes.updateMany(
{ isActive: true },
{ $inc: { level: 1 } }
)
Use bulkWrite when:
- You want to perform different updates on different documents.
- You need high performance when applying thousands of operations.
- You want multiple operation types (insert, update, delete) in one batch.
- You need fine-grained control over each write.
db.heroes.bulkWrite([
{
updateOne: {
filter: { name: "Aarav" },
update: { $inc: { level: 1 } }
}
},
{
updateOne: {
filter: { team: "Alpha" },
update: { $set: { uniform: "Blue" } }
}
},
{
deleteOne: {
filter: { isActive: false }
}
}
])
Summary:
updateMany → simple, one-update-to-all
bulkWrite → complex, different operations in one batch
Error Handling Examples (Important)
1. What happens when a filter matches 0 documents?
If your filter does not match anything, MongoDB will NOT throw an error. It simply returns:
{
acknowledged: true,
matchedCount: 0,
modifiedCount: 0
}
Example:
db.heroes.updateOne(
{ name: "NonExistingHero" },
{ $set: { level: 99 } }
)
Good practice: Always check matchedCount.
const result = db.heroes.updateOne(...)
if (result.matchedCount === 0) {
print("⚠ No hero found with that filter!")
}
2. What if you use deleteOne with a non-matching filter?
Result:
{ acknowledged: true, deletedCount: 0 }
3. What if update operation is malformed?
Example of incorrect update (missing $ operator):
db.heroes.updateOne(
{ name: "Aarav" },
{ level: 20 } // ❌ wrong
)
This throws:
MongoServerError: The update operation document must contain atomic operators
4. How to safely test updates?
Always run a preview first:
db.heroes.find({ team: "Alpha" })
This prevents accidental mass updates.
Part 9: Cheat Sheet (Print & Stick!)
| Command | What It Does |
|---|---|
| updateOne(filter, update) | Change 1 document |
| updateMany(filter, update) | Change many |
| $set: { field: value } | Set field |
| $inc: { field: 1 } | Increase number |
| $push: { array: value } | Add to array |
| deleteOne(filter) | Delete 1 |
| deleteMany(filter) | Delete many |
| drop() | Delete collection |
Part 10: Common Mistakes & Fixes
| Mistake | Fix |
|---|---|
| Forgetting $set | Always use $set to change fields |
| Using = instead of $set | Wrong! Use { $set: { level: 6 } } |
| No filter → updates all | Always add { name: "X" } |
| drop() by mistake | No undo! Backup first |
Final Words
You’re a Data Artist!
You just:
- Used pencil (updateOne, $set, $inc)
- Used eraser (deleteOne, drop)
- Edited in shell and GUI
- Learned pro tricks like upsert, pipelines
Your Mission:
db.heroes.updateOne(
{ name: "You" },
{ $set: { power: "MongoDB Master", level: 100 } },
{ upsert: true }
)
Your Task:
"Add a new power to all heroes with level >= 6 and remove inactive ones."
You just added yourself as a hero!
You’re now a Certified MongoDB Editor!
Resources
- Update Docs (MongoDB Update Documents)
- Delete Docs (MongoDB Remove / Delete Documents)
- Compass Edit (How to Modify Documents in MongoDB Compass)
- Delete Methods Reference (deleteOne, deleteMany, etc.)
Before You Leave : Become a MongoDB Hero
If this tutorial helped you:
- Share it with a friend learning databases
- Leave a comment below
- Bookmark this post for quick reference
Want more lessons? Tell me in the comments what you want next:
- MongoDB Aggregation
- Joins & Lookup
- Indexing for Speed
- Real World MongoDB Projects
Stay curious, hero. Your MongoDB journey has just begun. ⚡
Keep drawing in your magic notebook.
No comments:
Post a Comment