What are MongoDB Update Operators?

If you are interested to learn about the MongoDB Query Update

MongoDB Update Operators

There are many update operators that can be used during document updates.

{
   <operator1>: { <field1>: <value1>, ... },
   <operator2>: { <field2>: <value2>, ... },
   ...
}

Behavior

Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order.

In MongoDB 4.4 and earlier, update operators process all document fields in lexicographic order.

Consider this example $set command:

{ $set: { "a.2": <new value>, "a.10": <new value>, } }

In MongoDB 5.0 and later, "a.2" is processed before "a.10" because 2 comes before 10 in numeric order.

In MongoDB 4.4 and earlier, "a.10" is processed before "a.2" because 10 comes before 2 in lexicographic order.

Fields

The following operators can be used to update fields:

  • $currentDate: Sets the field value to the current date
  • $inc: Increments the field value
  • $rename: Renames the field
  • $set: Sets the value of a field
  • $unset: Removes the field from the document

Array

The following operators assist with updating arrays.

  • $addToSet: Adds distinct elements to an array
  • $pop: Removes the first or last element of an array
  • $pull: Removes all elements from an array that match the query
  • $push: Adds an element to an array

Modifiers

NameDescription
$eachModifies the $push and $addToSet operators to append multiple items for array updates.
$positionModifies the $push operator to specify the position in the array to add elements.
$sliceModifies the $push operator to limit the size of updated arrays.
$sortModifies the $push operator to reorder documents stored in an array.

Bitwise

NameDescription
$bitPerforms bitwise ANDOR, and XOR updates of integer values.
What are MongoDB Update Operators?
Show Buttons
Hide Buttons