Before updating data, ensure you're using the correct database.
use myDatabase
To see what data exists before updating, use:
db.users.find().pretty()
To update a single document, use updateOne().
db.users.updateOne(
{ name: "John Doe" },
{ $set: { age: 35 } }
)
To update all matching documents, use updateMany().
db.users.updateMany(
{ city: "New York" },
{ $set: { status: "Active" } }
)
If you want to completely replace a document, use replaceOne().
db.users.replaceOne(
{ name: "Alice" },
{ name: "Alice Brown", age: 28, city: "Chicago" }
)
MongoDB provides various operators for updates:
$inc)db.users.updateOne(
{ name: "John Doe" },
{ $inc: { age: 1 } }
)
✅ Increases John's age by 1.
$set)db.users.updateOne(
{ name: "Alice" },
{ $set: { occupation: "Engineer" } }
)
✅ Adds an occupation field if it doesn't exist.
$unset)db.users.updateOne(
{ name: "John Doe" },
{ $unset: { age: "" } }
)
After updating, check if the data has changed:
db.users.find({ name: "John Doe" }).pretty()
You’ve learned how to update data in MongoDB using:
✅ updateOne() – Updates the first matching document.
✅ updateMany() – Updates all matching documents.
✅ replaceOne() – Replaces an entire document.
✅ Update operators like $set, $inc, and $unset.
Now, try updating documents in MongoDB with these techniques! 🚀