Database
NoSQL
MongoDB
Operators
Update Operators

Update Operators in MongoDB

MongoDB provides a range of update operators designed for modifying documents within a collection. These operators can be used with various update methods such as updateMany() and findAndModify(). They are compatible with MongoDB Atlas, MongoDB Enterprise, and MongoDB Community editions.

Syntax

To use update operators, you specify the operator expression within a document. The basic structure involves listing the operators and their associated field values.

Update Operators

General Operators

  • $currentDate: Sets a field to the current date, either as a Date or Timestamp. This operator is useful for updating timestamps.
db.collection.updateOne(
  { _id: 1 },
  { $currentDate: { lastModified: true } }
);
  • $inc: Increments the value of a field by a specified amount. If the field doesn’t exist, it will be created with the incremented value.
db.collection.updateOne(
  { _id: 1 },
  { $inc: { count: 5 } }
);
  • $min: Updates a field only if the specified value is less than the existing field value. This ensures that only smaller values update the field.
db.collection.updateOne(
  { _id: 1 },
  { $min: { score: 85 } }
);
  • $max: Updates a field only if the specified value is greater than the existing field value. This is used to keep the maximum value.
db.collection.updateOne(
  { _id: 1 },
  { $max: { score: 95 } }
);
  • $mul: Multiplies the value of a field by a specified amount. It allows for scaling of the field’s value.
db.collection.updateOne(
  { _id: 1 },
  { $mul: { price: 1.1 } }
);
  • $rename: Changes the name of a field in a document. This operator is useful for restructuring documents.
db.collection.updateOne(
  { _id: 1 },
  { $rename: { "oldFieldName": "newFieldName" } }
);
  • $set: Assigns a new value to a field. If the field does not exist, it is created with this new value.
db.collection.updateOne(
  { _id: 1 },
  { $set: { field: "newValue" } }
);
  • $setOnInsert: Sets the value of a field only if the update operation results in an insertion of a new document. It does not affect documents that are merely updated.
db.collection.updateOne(
  { _id: 1 },
  { $setOnInsert: { createdAt: new Date() } },
  { upsert: true }
);
  • $unset: Removes a specified field from a document. This is used for cleaning up or removing unnecessary fields.
db.collection.updateOne(
  { _id: 1 },
  { $unset: { fieldToRemove: "" } }
);

Array Operators

  • $: A positional operator that acts as a placeholder to update the first element matching the query condition.
db.collection.updateOne(
  { _id: 1, "items.name": "item1" },
  { $set: { "items.$.quantity": 10 } }
);
  • $[]: A placeholder operator that updates all elements in an array for documents matching the query condition.
db.collection.updateMany(
  { _id: 1 },
  { $set: { "items.$[].quantity": 10 } }
);
  • $[<identifier>]: A placeholder for updating all array elements matching a specified arrayFilters condition.
db.collection.updateMany(
  { _id: 1 },
  { $set: { "items.$[elem].quantity": 10 } },
  { arrayFilters: [{ "elem.name": "item1" }] }
);
  • $addToSet: Adds elements to an array only if they do not already exist, ensuring that duplicates are avoided.
db.collection.updateOne(
  { _id: 1 },
  { $addToSet: { tags: "newTag" } }
);
  • $pop: Removes the first or last item from an array, depending on the specified direction.
db.collection.updateOne(
  { _id: 1 },
  { $pop: { items: 1 } } // Removes the last item
);
  • $pull: Removes all elements from an array that match a given query condition, useful for filtering array contents.
db.collection.updateOne(
  { _id: 1 },
  { $pull: { items: { quantity: { $lt: 10 } } } }
);
  • $push: Appends an item to an array. This operator can be used to add elements dynamically.
db.collection.updateOne(
  { _id: 1 },
  { $push: { items: { name: "item2", quantity: 20 } } }
);
  • $pullAll: Removes all instances of specified values from an array.
db.collection.updateOne(
  { _id: 1 },
  { $pullAll: { items: [{ name: "item1" }] } }
);

Modifiers for Arrays

  • $each: Works with $push and $addToSet to append multiple items to an array in one operation.
db.collection.updateOne(
  { _id: 1 },
  { $push: { items: { $each: [{ name: "item3" }, { name: "item4" }] } } }
);
  • $position: Specifies the position in the array where elements should be added, used with $push.
db.collection.updateOne(
  { _id: 1 },
  { $push: { items: { $each: [{ name: "item5" }], $position: 1 } } }
);
  • $slice: Limits the size of arrays by controlling the number of elements when using $push.
db.collection.updateOne(
  { _id: 1 },
  { $push: { items: { $each: [{ name: "item6" }], $slice: 5 } } }
);
  • $sort: Reorders elements in an array when used with $push.
db.collection.updateOne(
  { _id: 1 },
  { $push: { items: { $each: [{ name: "item7" }], $sort: { name: 1 } } } }
);

Bitwise Operator

  • $bit: Performs bitwise operations such as AND, OR, and XOR on integer values, allowing for low-level data manipulation.
db.collection.updateOne(
  { _id: 1 },
  { $bit: { flags: { and: 1 } } }
};

Behavior

Starting with MongoDB 5.0, fields in update operations are processed in a specific order: string-based field names are processed lexicographically, while numeric names are processed numerically. This ordering affects how operators interact with fields during an update.

Conclusion

MongoDB’s update operators provide versatile and powerful tools for document modification. Understanding these operators and how they interact with document fields enables efficient data updates and management in MongoDB collections.