MongoDB Update
Operators
Field
s
The following operators can be used to update fields:
•$inc: Increments the field value
•$rename: Renames the field
•$set: Sets the value of a field
•$unset: Removes the field from the document
$inc: Increments the field value
// Incrementing 'age' by 1 for a specific student (e.g., Bob)
db.students.updateOne({ name: 'Bob' }, { $inc: { age: 1 } })
This will increase Bob's age by 1.
$rename: Renames the field
// Renaming 'grade' field to 'performance' for a specific student (e.g.,
Charlie)
db.students.updateOne({ name: 'Charlie' }, { $rename: { grade:
'performance' } })
This will rename the grade field to performance in Charlie's document.
$set: Sets the value of a field
// Setting 'grade' to 'B+' for a specific student (e.g., Daisy)
db.students.updateOne({ name: 'Daisy' }, { $set: { grade: 'B+' } })
This sets Daisy's grade to 'B+'.
$unset: Removes the field from the document
// Removing the 'courses' field entirely for a specific student (e.g.,
Nora)
db.students.updateOne({ name: 'Nora' }, { $unset: { courses: "" } })
This removes the courses field from Nora's document entirely.
Array
•$addToSet: Adds distinct elements to an array
•$pop: Removes the first or last element of an array
•$pull: Removes all elements from an array that match the query
•$push: Adds an element to an array
1. $addToSet: Adds distinct elements to an array
Let's add a new course, 'Art History', to Daisy's courses array, ensuring
no duplicates are added:
db.students.updateOne({ name: 'Daisy' }, { $addToSet: { courses: 'Art
History' } })
This will add 'Art History' to Daisy's courses array if it doesn't already
exist, ensuring uniqueness.
2. $pop: Removes the first or last element of an array
Suppose we want to remove the last course from Nora's courses array:
db.students.updateOne({ name: 'Nora' }, { $pop: { courses: 1 } })
This will remove the last element from Nora's courses array.
3. $pull: Removes all elements from an array that match
the query
Let's remove all occurrences of 'Physics' from Oscar's courses:
db.students.updateOne({ name: 'Oscar' }, { $pull: { courses: 'Physics' } })
This will remove all instances of 'Physics' from Oscar's courses array.
4. $push: Adds an element to an
array
Suppose we want to add a new course, 'Sociology', to Oscar's courses
array:
db.students.updateOne
({ name: 'Oscar' }, { $push: { courses: 'Sociology' } })
This will append 'Sociology' to Oscar's courses array.