MongoDB Tutorial menu

MongoDB Update and Delete

updateOne() and updateMany() change documents, and deleteOne() and deleteMany() remove them.

updateOne() with $set

An update takes a filter (which documents) and an update (what to change). $set sets the value of a field, and adds the field if it does not exist.

Hamza has chosen the Digital Marketing course:

Example

javascript
db.students.updateOne(
  { name: "Hamza Raza" },
  { $set: { course: "Digital Marketing", skills: ["SEO"] } }
)
Output
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
  • matchedCount: how many documents matched the filter
  • modifiedCount: how many actually changed

updateOne changes only the first document that matches, even if more match.

updateMany()

Give 2 grace marks to every student in Karachi:

Example

javascript
db.students.updateMany(
  { city: "Karachi" },
  { $inc: { marks: 2 } }
)
Output
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 3,
  modifiedCount: 3,
  upsertedCount: 0
}

Update Operators

OperatorWhat it doesExample
$setSet a field's value{ $set: { city: "Lahore" } }
$unsetRemove a field{ $unset: { skills: "" } }
$incAdd to a number (use a negative number to subtract){ $inc: { marks: 5 } }
$mulMultiply a number{ $mul: { fee: 0.9 } }
$renameRename a field{ $rename: { marks: "score" } }
$pushAdd an item to an array{ $push: { skills: "React" } }
$addToSetAdd an item only if it is not already there{ $addToSet: { skills: "CSS" } }
$pullRemove matching items from an array{ $pull: { skills: "CSS" } }

Ali has learned a new skill:

Example

javascript
db.students.updateOne({ name: "Ali Khan" }, { $push: { skills: "JavaScript" } })

db.students.findOne({ name: "Ali Khan" }, { _id: 0, skills: 1 })
Output
{ skills: [ 'HTML', 'CSS', 'JavaScript' ] }

Always use an operator such as $set. If you pass a plain document as the update, like { marks: 90 }, updateOne refuses it with an error, because that would replace the whole document. To replace a document on purpose, use replaceOne().

replaceOne()

replaceOne() swaps the whole document (except _id) for a new one:

Example

javascript
db.courses.replaceOne(
  { _id: "WEB" },
  { title: "Web Development", months: 6, mode: ["Online", "On campus"] }
)

Any old field not in the new document is gone.

Upsert

With upsert: true, if nothing matches, MongoDB inserts a new document instead:

Example

javascript
db.students.updateOne(
  { name: "Zainab Shah" },
  { $set: { city: "Karachi", age: 19, marks: 0 } },
  { upsert: true }
)
Output
{
  acknowledged: true,
  insertedId: ObjectId('6710a1f2c3b4d5e6f7a8b907'),
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}

The new document gets the name from the filter plus the $set fields.

Delete Documents

deleteOne() removes the first match; deleteMany() removes all matches:

Example

javascript
db.students.deleteOne({ name: "Zainab Shah" })
Output
{ acknowledged: true, deletedCount: 1 }

Example

javascript
db.students.deleteMany({ marks: { $lt: 50 } })
Output
{ acknowledged: true, deletedCount: 0 }

No student has less than 50 marks, so nothing was deleted.

db.students.deleteMany({}) with an empty filter deletes every document in the collection. Before deleting, run find() with the same filter to see exactly what will be removed.

Summary

TaskMethod
Change the first matchupdateOne(filter, update)
Change all matchesupdateMany(filter, update)
Replace a whole documentreplaceOne(filter, newDoc)
Update or insertupdateOne(filter, update, { upsert: true })
Remove the first matchdeleteOne(filter)
Remove all matchesdeleteMany(filter)

Exercise

Exercise

Which update adds 5 to Sana's marks?

Learn MongoDB with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp