MongoDB mongosh Update

MongoDB mongosh – Update Documents ✏️

In MongoDB, update operations are used to modify existing documents in a collection.

MongoDB provides powerful update methods with update operators.


1️⃣ Update a Single Document (updateOne)

Syntax

db.collection.updateOne(filter, update, options)

Example

db.students.updateOne(
{ name: "Amit" },
{ $set: { age: 23 } }
)

Output

matchedCount: 1
modifiedCount: 1

2️⃣ Update Multiple Documents (updateMany)

db.students.updateMany(
{ course: "BA" },
{ $set: { status: "active" } }
)

3️⃣ Update with Multiple Fields

db.students.updateOne(
{ name: "Riya" },
{ $set: { age: 21, course: "BSc" } }
)

4️⃣ Important Update Operators

$set – Set / change value

{ $set: { age: 25 } }

$inc – Increment value

db.students.updateOne(
{ name: "Amit" },
{ $inc: { age: 1 } }
)

$unset – Remove field

db.students.updateOne(
{ name: "Karan" },
{ $unset: { phone: "" } }
)

5️⃣ Update Arrays

$push – Add element

db.students.updateOne(
{ name: "Rahul" },
{ $push: { skills: "MongoDB" } }
)

$pull – Remove element

db.students.updateOne(
{ name: "Rahul" },
{ $pull: { skills: "HTML" } }
)

6️⃣ Replace Document (replaceOne)

⚠️ Replaces the entire document (except _id)

db.students.replaceOne(
{ name: "Neha" },
{ name: "Neha", age: 20, course: "BA" }
)

7️⃣ Upsert (Update or Insert)

If document doesn’t exist, it will be inserted.

db.students.updateOne(
{ name: "Suman" },
{ $set: { age: 22, course: "BCom" } },
{ upsert: true }
)

8️⃣ Update Using Conditions

db.students.updateMany(
{ age: { $gt: 22 } },
{ $set: { senior: true } }
)

SQL vs MongoDB (UPDATE)

SQL

UPDATE students SET age = 23 WHERE name = 'Amit';

MongoDB

db.students.updateOne(
{ name: "Amit" },
{ $set: { age: 23 } }
)

Common Mistakes ⚠️

  • Forgetting update operators ($set, $inc)

  • Using updateOne() when updateMany() is needed

  • Accidentally replacing full document


Quick Summary 🧠

updateOne() // update single document
updateMany() // update multiple documents
$set, $inc // update operators
upsert // update or insert

You may also like...