Create New Post

MongoDB - Update Operators

MongoDB provides update operators to perform specific modifications on documents during the update process. Here are some common MongoDB update operators:

$set Operator:

The $set operator updates the value of a field:

db.collection_name.updateOne( { filter_criteria }, { $set: { field: new_value } } );

$unset Operator:

The $unset operator removes a field from a document:

db.collection_name.updateOne( { filter_criteria }, { $unset: { field_to_remove: "" } } );

$inc Operator:

The $inc operator increments the value of a field:

db.collection_name.updateOne( { filter_criteria }, { $inc: { numeric_field: increment_value } } );

$mul Operator:

The $mul operator multiplies the value of a field:

db.collection_name.updateOne( { filter_criteria }, { $mul: { numeric_field: multiplier } } );

$rename Operator:

The $rename operator renames a field:

db.collection_name.updateOne( { filter_criteria }, { $rename: { old_field: new_field } } );

$min and $max Operators:

The $min operator updates the value of a field if the specified value is less than the existing value:

db.collection_name.updateOne( { filter_criteria }, { $min: { numeric_field: new_min_value } } );

The $max operator updates the value of a field if the specified value is greater than the existing value:

db.collection_name.updateOne( { filter_criteria }, { $max: { numeric_field: new_max_value } } );

$addToSet Operator:

The $addToSet operator adds elements to an array if they are not already present:

db.collection_name.updateOne( { filter_criteria }, { $addToSet: { array_field: new_element } } );

$push Operator:

The $push operator appends an element to an array:

db.collection_name.updateOne( { filter_criteria }, { $push: { array_field: new_element } } );

$pull Operator:

The $pull operator removes elements from an array based on a specified condition:

db.collection_name.updateOne( { filter_criteria }, { $pull: { array_field: element_to_remove } } );

These update operators can be used with the updateOne or updateMany methods to modify documents in a collection based on specific criteria.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

81513