Lecture Note Of Day 7:
MongoDB CRUD Operations – Part 3 (Update)
Objective:
To understand how to update documents in MongoDB using the updateOne(), updateMany(), and replaceOne() methods.
Outcome:
By the end of this lesson, students will be able to use MongoDB's update methods to modify existing documents in a collection.
1. Introduction to MongoDB Update Operations
MongoDB provides several methods to update documents in a collection. These operations allow us to modify the data within a document based on certain conditions.
There are three primary update operations:
- updateOne()
- updateMany()
- replaceOne()
Each of these operations offers flexibility for updating single or multiple documents, as well as completely replacing a document.
2. Basic Syntax for Update Operations
General Syntax for Update Methods:
db.collection.updateOne(filter, update, options)
db.collection.updateMany(filter, update, options)
db.collection.replaceOne(filter, replacement, options)
- filter: The condition to match the document(s) to be updated.
- update: The changes you want to make to the matching document(s). This can include operators like $set, $inc, $push, etc.
- replacement: Used in replaceOne(), the entire document replaces the matched document.
- options: Additional settings like upsert (insert if the document doesn't exist).
3. The updateOne() Method
The updateOne() method is used to update a single document that matches a specific filter. If multiple documents match the filter, only the first document is updated.
Syntax:
db.collection.updateOne(
{ <filter> }, // Filter to match the document
{ <update> }, // Update operation (e.g., $set)
{ <options> } // Optional settings like upsert
)
Example:
Updating a student's grade in the students collection:
db.students.updateOne(
{ name: "John" }, // filter
{ $set: { grade: "A+" } } // update
)
This will update the first student document where name is "John" and set their grade to "A+".
4. The updateMany() Method
The updateMany() method is used to update multiple documents that match the specified filter. This is useful when you need to apply changes to more than one document.
Syntax:
db.collection.updateMany(
{ <filter> }, // Filter to match the documents
{ <update> }, // Update operation
{ <options> } // Optional settings
)
Example:
If we want to give a 5% increase in the grade of all students in class "101":
db.students.updateMany(
{ class_id: 101 }, // filter: match all students in class 101
{ $set: { grade: "A" } } // update: set grade to "A"
)
This will update all students in class 101 and set their grade to "A".
5. The replaceOne() Method
The replaceOne() method is used to completely replace a document. Unlike updateOne() or updateMany(), this method does not allow you to update specific fields. Instead, it replaces the entire document with the new document provided.
Syntax:
db.collection.replaceOne(
{ <filter> }, // Filter to match the document
{ <replacement> }, // New document to replace the matched document
{ <options> } // Optional settings
)
Example:
Let's say you want to completely replace the details of a student with the name "John":
db.students.replaceOne(
{ name: "John" }, // filter: match the document where name is "John"
{ name: "John", grade: "B", class_id: 102, age: 22 } // new document
)
This will replace the entire document of the student named "John" with the new details.
6. Update Operators
In MongoDB, when updating documents, we can use several update operators. Some of the most common ones include:
- $set: Used to set the value of a field. If the field does not exist, it will be added.
{ $set: { field: value } }
- $inc: Used to increment a field's value (e.g., increase age by 1).
{ $inc: { age: 1 } }
- $push: Adds an element to an array field.
{ $push: { courses: "Math" } }
- $pull: Removes an element from an array field.
{ $pull: { courses: "History" } }
- $rename: Renames a field.
{ $rename: { "oldField": "newField" } }
- $unset: Removes a field from a document.
{ $unset: { field: "" } }
7. Using the upsert Option
The upsert option is used in the updateOne(), updateMany(), and replaceOne() methods. When set to true, MongoDB will insert a new document if no document matches the filter.
Example:
If you want to update a student’s grade, but if the student doesn’t exist, you want to insert a new student document:
db.students.updateOne(
{ name: "John" }, // filter: match "John"
{ $set: { grade: "A" } }, // update: set grade to "A"
{ upsert: true } // upsert: insert if not found
)
8. Summary of Update Methods
Method | Description | Use Case |
updateOne() | Updates a single document that matches the filter. | Update a single document. |
updateMany() | Updates all documents that match the filter. | Update multiple documents. |
replaceOne() | Completely replaces a single document. | Replace an entire document. |
9. Common Errors
- Unrecognized Operator: Using an invalid operator in the update object will result in an error.
- Missing Fields: Trying to update a field that does not exist can lead to unexpected behavior unless the $set operator is used.
- Invalid Data Types: Ensure that the values being updated match the expected data type of the field (e.g., trying to update a string field with a number).
10. Practice Exercises
Exercise 1:
Update the grade of the student with name "Alice" to "B+".
Exercise 2:
Update all students in class "102" to have a grade of "A".
Exercise 3:
Replace the entire document of the student named "Bob" with new details: { name: "Bob", grade: "B", class_id: 103, age: 25 }.
Exercise 4:
Use the $inc operator to increment the age of the student named "John" by 1 year.
Exercise 5:
Add a new course "Science" to the courses array of the student with name "Charlie".
Conclusion:
In this lesson, we covered how to perform update operations in MongoDB using the updateOne(), updateMany(), and replaceOne() methods.
