Update Operator

The following modifiers are available to update operations. For example - in db.collection.update() and db.collection.findAndModify().

Defines the operator expression in the document of the form:

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

Field Operator

$currentDate

It updates the elements of a field to the current date, either as a Date or a timestamp. The default data type of this operator is the date.

Syntax:

snippet
{ $currentDate: { <field1>: <typeSpecification1>, ... } }

Example:

snippet
db.books.insertOne(
   { _id: 1, status: "a", lastModified: purchaseDate("2013-10-02T01:11:18.965Z") }
)

$inc

It increases a filed by the specified value.

Syntax:

snippet
{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

Example:

snippet
{
  _id: 000438,
  sku: "MongoDB",
  quantity: 1,
  metrics: {
    orders: 2,
    ratings: 3.5
  }
}

$min

It changes the value of the field to a specified value if the specified value is less than the current value of the filed.

Syntax:

snippet
{ $min: { <field1>: <value1>, ... } }

Example:

snippet
{ _id: 0021, highprice: 800, lowprice: 200 }
db.books.update( { _id: 0021 }, { $min: { highprice: 500 } } )

$max

It changes the value of the field to a specified value if the specified value is greater than the current value of the filed.

Syntax:

snippet
{ $max: { <field1>: <value1>, ... } }

Example:

snippet
{ _id: 0021, highprice: 800, lowprice: 200 }
db.books.update( { _id: 0021 }, { $max: { highprice: 950 } } )

$mul

It multiplies the value of a field by a number.

Syntax:

snippet
{ $mul: { <field1>: <number1>, ... } }

Example:

snippet
db.books.update(
   { _id: 1 },
   { $mul: { price: NumberDecimal("180.25"), qty: 2 } }
)

$rename

The rename operator changes the name of a field.

Syntax:

snippet
{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }

Example:

snippet
db.books.updateMany( {}, { $rename: { "nmae": "name" } } )

$set

The set operator changes the value of a field with the specified value.

Syntax:

snippet
{ $set: { <field1>: <value1>, ... } }

Example:

snippet
{
  _id: 100,
  sku: "abc123",
  quantity: 50,
  instock: true,
  reorder: false,
  details: { model: "14Q2", make: "xyz" },
  tags: [ "technical", "non technical" ],
  ratings: [ { by: "ijk", rating: 4 } ]
}

$setOnInsert

If the upsert is set to true, then it results in an insert of a document, then setOnInsert operator assigns the specified values to the field in the document.

Syntax:

snippet
db.collection.update(
   <query>,
   { $setOnInsert: { <field1>: <value1>, ... } },
   { upsert: true }
)

$unset

It removes a specified field.

Syntax:

snippet
{ $unset: { <field1>: "", ... } }

Example:

snippet
db.products.update(
   { sku: "unknown" },
   { $unset: { quantity: "", instock: "" } }
)

Array Operators

$

We can update an element in an array without explicitly specifying the position of the element.

Syntax:

snippet
{ "<array>.$" : value }

Example:

snippet
db.collection.update(
   { <array>: value ... },
   { <update operator>: { "<array>.$" : value } }
)

$[ ]

The positional operator indicates that the update operator should change all the elements in the given array field.

Syntax:

snippet
{ <update operator>: { "<array>.$[]" : value } }

Example:

snippet
db.collection.updateMany(
   { <query conditions> },
   { <update operator>: { "<array>.$[]" : value } }
)

$[<identifier>]

It is called a filtered positional operator that identifies the array elements.

Syntax:

snippet
{ <update operator>: { "<array>.$[<identifier>]" : value } },
{ arrayFilters: [ { <identifier>: <condition> } ] }

Example:

snippet
db.collection.updateMany( { <query conditions> },
   { <update operator>: { "<array>.$[<identifier>]" : value } },
   { arrayFilters: [ { <identifier>: <condition> } ] } )

$addToSet

It adds an element to an array unless the element is already present, in which case this operator does nothing to that array.

Syntax:

snippet
{ $addToSet: { <field1>: <value1>, ... } }

Example:

snippet
db.books.update(
   { _id: 1 },
   { $addToSet: { tags: "MongoDB" } }
)

$pop

We can remove the first or last element of an array using the pop operator. We need to pass the value of pop as -1 to remove the first element of an array and 1 to remove the last element in an array.

Syntax:

snippet
{ $pop: { <field>: <-1 | 1>, ... } }

Example:

snippet
db.books.update( { _id: 1 }, { $pop: { mongoDB: -1 } } )

$pull

Using a pull operator, we can remove all the instances of a value in an array that matches the specified condition.

Syntax:

snippet
{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }

Example:

snippet
db.books.update( { }, { $pull: { Development: { $in:["Java", "RDBMS" ] }, Tech: "Cybersecurity" } },
    { multi: true }
)

$push

It appends a specified value to an array.

Syntax:

snippet
{ $push: { <field1>: <value1>, ... } }

Example:

snippet
db.students.update( { _id: 9 }, { $push: { scores: 91 } } )

$pullAll

We can remove all instances of the specified value from an existing array using the pullAll operator. It removes elements that match the listed value.

Syntax:

snippet
{ $pullAll: { <field1>: [ <value1>, <value2> ... ], ... } }

Example:

snippet
db.survey.update( { _id: 1 }, { $pullAll: { scores: [ 0, 5 ] } } )

Modifiers

$each

It is used with the $addToSet operator and the $push operator. It is used with the addToSet operator to add multiple values to an array if the value does not exist in the field.

Syntax:

snippet
{ $addToSet: { <field>: { $each: [ <value1>, <value2> ... ] } } }

It is used with the push operator to append multiple values to an array.

Syntax:

snippet
{ $push: { <field>: { $each: [ <value1>, <value2> ... ] } } }

Example:

snippet
db.students.update( { name: "Akki" }, { $push: { scores: { $each: [ 90, 92, 85 ] } } } )

$position

It specifies the location where the push operator inserts elements inside an array.

Syntax:

snippet
{
  $push: {
    <field>: {
       $each: [ <value1>, <value2>, ... ],
       $position: <num>
    }
  }
}

Example:

snippet
db.students.update(
   { _id: 1 },
   {
     $push: {
        scores: {
           $each: [ 50, 60, 70 ],
           $position: 0
        }
     }
   }
)

$slice

This modifier is used to limit the number of array elements during the push operation.

Syntax:

snippet
{
  $push: {
     <field>: {
       $each: [ <value1>, <value2>, ... ],
       $slice: <num>
     }
  }
}

Example:

snippet
db.students.update(
   { _id: 1 },
   {
     $push: {
       scores: {
         $each: [ 80, 78, 86 ],
         $slice: -5
       }
     }
   }
)

$sort

The sort modifier arranges the values of an array during the push operation.

Syntax:

snippet
{
  $push: {
     <field>: {
       $each: [ <value1>, <value2>, ... ],
       $sort: <sort specification>
     }
  }
}

Example:

snippet
db.students.update(
   { _id: 1 },
   {
     $push: {
       quizzes: {
         $each: [ { id: 3, score: 8 }, { id: 4, score: 7 }, { id: 5, score: 6 } ],
         $sort: { score: 1 }
       }
     }
   }
)

Bitwise Operator

$bit

The bit operator updates a field using a bitwise operation. It supports bitwise AND, bitwise OR, and bitwise XOR operations.

Syntax:

snippet
{ $bit: { <field>: { <and|or|xor>: <int> } } }

Example:

snippet
db.books.update( { _id: 1 }, { $bit: { expdata: { and: price(100) } } }
)
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +