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
db.students.updateOne(
{ name: "Hamza Raza" },
{ $set: { course: "Digital Marketing", skills: ["SEO"] } }
){
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}matchedCount: how many documents matched the filtermodifiedCount: 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
db.students.updateMany(
{ city: "Karachi" },
{ $inc: { marks: 2 } }
){
acknowledged: true,
insertedId: null,
matchedCount: 3,
modifiedCount: 3,
upsertedCount: 0
}Update Operators
| Operator | What it does | Example |
|---|---|---|
$set | Set a field's value | { $set: { city: "Lahore" } } |
$unset | Remove a field | { $unset: { skills: "" } } |
$inc | Add to a number (use a negative number to subtract) | { $inc: { marks: 5 } } |
$mul | Multiply a number | { $mul: { fee: 0.9 } } |
$rename | Rename a field | { $rename: { marks: "score" } } |
$push | Add an item to an array | { $push: { skills: "React" } } |
$addToSet | Add an item only if it is not already there | { $addToSet: { skills: "CSS" } } |
$pull | Remove matching items from an array | { $pull: { skills: "CSS" } } |
Ali has learned a new skill:
Example
db.students.updateOne({ name: "Ali Khan" }, { $push: { skills: "JavaScript" } })
db.students.findOne({ name: "Ali Khan" }, { _id: 0, skills: 1 }){ 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
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
db.students.updateOne(
{ name: "Zainab Shah" },
{ $set: { city: "Karachi", age: 19, marks: 0 } },
{ upsert: true }
){
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
db.students.deleteOne({ name: "Zainab Shah" }){ acknowledged: true, deletedCount: 1 }Example
db.students.deleteMany({ marks: { $lt: 50 } }){ 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
| Task | Method |
|---|---|
| Change the first match | updateOne(filter, update) |
| Change all matches | updateMany(filter, update) |
| Replace a whole document | replaceOne(filter, newDoc) |
| Update or insert | updateOne(filter, update, { upsert: true }) |
| Remove the first match | deleteOne(filter) |
| Remove all matches | deleteMany(filter) |
Exercise
Exercise
Which update adds 5 to Sana's marks?
