To update a document in MongoDB, we can use the ‘updateOne‘ or ‘updateMany‘ method, depending on whether we want to update a single document or multiple documents in a collection. The general syntax of the ‘updateOne‘ method is as follows:
db.collection.updateOne(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string> // Available starting in MongoDB 4.2.1
}
)
where:
- ‘<filter>‘ is a document that matches the filter for the document or documents to update.
- ‘<update>‘ is a document containing update operators and their corresponding values.
Some common update operators in MongoDB are:
1. ‘$set‘: Sets the value of a field in a document. For example, to set the value of the field ‘score‘ to 90 in a document that matches a certain filter, we can use the following update operation:
db.collection.updateOne(
{ name: "John" },
{ $set: { score: 90 } }
)
2. ‘$unset‘: Removes a field from a document. For example, to remove the ‘score‘ field from a document that matches a certain filter, we can use the following update operation:
db.collection.updateOne(
{ name: "John" },
{ $unset: { score: "" } }
)
3. ‘$inc‘: Increments the value of a field by a specified amount. For example, to increment the value of the ‘score‘ field by 10 in a document that matches a certain filter, we can use the following update operation:
db.collection.updateOne(
{ name: "John" },
{ $inc: { score: 10 } }
)
4. ‘$push‘: Adds an element to an array field. For example, to add the element ‘"history"` to the ‘subjects‘ array field in a document that matches a certain filter, we can use the following update operation:
db.collection.updateOne(
{ name: "John" },
{ $push: { subjects: "history" } }
)
5. ‘$pull‘: Removes all occurrences of an element from an array field. For example, to remove all occurrences of the element ‘"math"` from the ‘subjects‘ array field in a document that matches a certain filter, we can use the following update operation:
db.collection.updateOne(
{ name: "John" },
{ $pull: { subjects: "math" } }
)
These are just some of the commonly used update operators in MongoDB. There are many more operators available, and they provide a powerful way to manipulate and update documents in our collections.