Update Operator
Update Operator
Operators
Field
s
The following operators can be used to update fields:
Let's add a new course, 'Art History', to Daisy's courses array, ensuring
no duplicates are added:
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:
This will remove the last element from Nora's courses array.
3. $pull: Removes all elements from an array that match
the query
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' } })