MONGODB Tutorial



MongoDB UPDATE


✏️ MongoDB Update Documents

The updateOne() and updateMany() methods are used to modify existing documents in a MongoDB collection.

🔸 updateOne()

Updates the first document that matches the filter.

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

This updates the age field to 25 for the first student named "Amit".

🔸 updateMany()

Updates all documents that match the filter.

db.students.updateMany(
  { age: { $lt: 18 } },
  { $set: { status: "minor" } }
);
  

This sets the status field to "minor" for all students younger than 18.

🔸 updateOne() with $inc Operator

Increment the age by 1 for a student named "Riya":

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

🔸 Replace Entire Document

Replace the whole document of the student named "Raj" (be careful with this):

db.students.replaceOne(
  { name: "Raj" },
  { name: "Raj", age: 23, status: "active" }
);
  

⚡ Quick Recap:

  • updateOne(filter, update) updates the first matching document.
  • updateMany(filter, update) updates all matching documents.
  • $set sets new values to fields.
  • $inc increments numeric fields.
  • replaceOne() replaces the entire document (careful with this!).
Tip: Always specify a filter carefully to avoid updating unintended documents.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review