MongoDB Update Operators:
MongoDB provides several update operators that allow you to modify documents in a collection. These operators offer flexible and powerful ways to update specific fields or elements within documents. Here are some commonly used update operators in MongoDB:
$set: Sets the value of a field in a document. If the field doesn't exist, it creates it.
- Example:
db.collection.updateOne({ _id: ObjectId("123") }, { $set: { name: "John" } })$unset: Removes a field from a document.
- Example:
db.collection.updateOne({ _id: ObjectId("123") }, { $unset: { age: "" } })$inc: Increments the value of a field by a specified amount.
- Example:
db.collection.updateOne({ _id: ObjectId("123") }, { $inc: { score: 10 } })$mul: Multiplies the value of a field by a specified amount.
- Example:
db.collection.updateOne({ _id: ObjectId("123") }, { $mul: { price: 1.1 } })$rename: Renames a field.
- Example:
db.collection.updateOne({ _id: ObjectId("123") }, { $rename: { "oldField": "ne$push: Adds an element to an array field.
- Example:
db.collection.updateOne({ _id: ObjectId("123") }, { $push: { scores: 85 } })$pop: Removes the first or last element from an array field.
- Example:
db.collection.updateOne({ _id: ObjectId("123") }, { $pop: { scores: 1 } }) // Removes the last element db.collection.updateOne({ _id: ObjectId("123") }, { $pop: { scores: -1 } }) //Removes the last element $addToSet: Adds an element to an array field only if it doesn't already exist.
- Example:
db.collection.updateOne({ _id: ObjectId("123") }, { $addToSet: { tags: "newTag"$pull: Removes all instances of a specified value from an array field.
- Example:
db.collection.updateOne({ _id: ObjectId("123") }, { $pull: { tags: "oldTag" } })These are just a few examples of the update operators available in MongoDB. You can use multiple operators together in a single update operation to perform complex updates on documents in a collection.



0 Comments