Fields, Array and Modifiers update operators in MongoDB

This article covers:

Fields update operators in MongoDB

$currentDate

Sets the value of a field to current date, either as a Date or a Timestamp. $currentDate takes the following values:

  • true or {$type: "date"}: to update or create the field in ISODate format.
  • {$type: "timestamp"}: to update or create the field in Timestamp format.
db.collection.update({query}, {$currentDate: { field: true|{$type: "date"|{$type: "timestamp"}}})

Example of $currentDate

Update all documents with a name equal to article and set the field lastModified to the current date.

db.articles.updateMany({name: "article"}, {$currentDate: {lastModified: {$type: "timestamp"}}})

$inc

Increments the value of the field by the specified amount.

db.collection.update({query}, {$inc: {field: value}})

Example of $inc

Update all documents with a name equal to article and increment the field views by one. If the field does not exist mongodb sets its value to 0 before incrementing.

db.articles.updateMany({name: "article"}, {$inc: {views: 1}})

$min

Only updates the field if the specified value is less than the existing field value.

db.collection.update({query}, {$min: {field: value}})

Example of $min

Update all documents with a name equal to article and reset the field views to 0 if the old views value is greater than 0.

db.articles.updateMany({name: "article"}, {$min: {views: 0}})

$max

Only updates the field if the specified value is greater than the existing field value.

db.collection.update({query}, {$max: {field: value}})

Example of $max

Update all documents with a name equal to article and set the field views to 20 if the old views value is less than 20.

db.articles.updateMany({name: "article"}, {$max: {views: 20}})
  • In both scenarios $min or $max if the field does not exist, mongodb create the new field with the values specified as a value in the update query.

  • The $max and $min can take non-numeric values.

  • When comparing two different type please refer to the order in the following link: Sort in MongoDB

$mul

Multiplies the value of the field by the specified amount.

db.collection.update({query}, {$mul: {field: value}})

Example of $mul

Update all documents with a name equal to article and multiply the views field by 5.

db.articles.updateMany({name: "article"}, {$mul: {views: 20}})

$rename

Renames a field.

db.collection.update({query}, {$rename: {field: value}})

Example of $rename

Update all documents with a name equal to article and change the name of the field categories to tags.

db.articles.updateMany({name: "article"}, {$rename: {categories: "tags"}})

$set

Sets the value of a field in a document.

db.collection.update({query}, {$set: {field: value}})

Example of $set

Update all documents with a name equal to article and set the value of the field views to 25.

db.articles.updateMany({name: "article"}, {$set: {views: 25}})

$setOnInsert

Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents. To see this in practice you should add the parameter upsert with a true value and use a query criteria that does not match any document inside your collection.

db.collection.update({query}, {$setOnInsert: {field: value}}, {upsert: true})

Example of $setOnInsert

Insert a document with a name equal to article and set the field views to 5 if the document is not found.

db.articles.updateMany({name: "article"}, {$setOnInsert: {views: 5}}, {upsert: true})

$unset

Removes the specified field from a document.

db.collection.update({query}, {field: {$unset: ""}})

Example of $unset

Update all documents with a name equal to article and remove the field views from the document.

db.articles.updateMany({name: "article"}, {$unset: {views: ""}})

Array update operators in MongoDB

$

Acts as a placeholder to update the first element that matches the query condition. You must include the array field as part of the query document so that MongoDb knows what values you want to update.

db.collection.update({query, "arrayField": {cond}}, {$operator: {"arrayField.$": value}})

Example of $

Update all documents with a name equal to article and an array tags containing hello and set the first matches value (a value that is equal to hello) to hi. If there is multiple values that matches hello, MongoDB will update only the first one. To update all the values please refer to $[] operator.

db.articles.updateMany({name: "article", tags: "hello"}, {$set: {"tags.$": "hi"}})

If the field is not found MongoDB will insert an object like this one: { "0" : "hi" }

$[]

Acts as a placeholder to update all elements in an array for the documents that match the query condition.

db.collection.update({query}, {$operator: {"arrayField.$[]": value}})

Example of $[]

Update all documents with a name equal to article and increment all the field values by 10.

db.articles.updateMany({name: "article"}, {$inc: {"views.$[]": 10}})

$[<identifier>]

Acts as a placeholder to update all elements that match the arrayFilters condition for the documents that match the query condition.

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

Example of $[<identifier>]

Update all documents with a name equal to article and increment the grades array values with 2 when the grade is greater than 16.

db.articles.updateMany(
	{name: "article"}, 
	{$inc: { "grades.$[gradeIncrement]": 2}},
	{ arrayFilters: [{gradeIncrement: {$gt: 16}}]}
)

$addToSet

Adds elements to an array only if they do not already exist in the set.

db.collection.update({query}, {$addToSet: {field: value}})

Example of $addToSet

Update all documents with a name equal to article and add the tag "sport" to the tags array if only it does not exists.

db.articles.updateMany({name: "article"}, {$addToSet: {tags: "sport"}})

$pop

Removes the first or last item of an array. Set the $pop value to -1 to remove the first element and 1 to remove the last element in an array

db.collection.update({query}, {$pop: {arrayField: -1|1}})

Example of $pop

Update all documents with a name equal to article and remove the first element from the tags array.

db.articles.updateMany({name: "article"}, {$pop: {tags: -1}})

$pull

Removes all array elements that match a specified query.

db.collection.update({query}, { $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } })

Example of $pull

Update all documents with a name equal to article and remove all the grades less than 10.

db.articles.updateMany({name: "article"}, {$pull: {grades: {$lt: 10}}})

$push

Adds an item to an array.

db.collection.update({query}, { $push: { <field1>: { <modifier1>: <value1>, ... }, ... } })

Example of $push

Update all documents with a name equal to article and add the "sport" tag to the list of tags.

db.articles.updateMany({name: "article"}, {$push: {tags: "sport"}})

Update all documents with a name equal to article and add the "sport" and "soccer" tag to the list of tags.

db.articles.updateMany({name: "article"}, {$push: {tags: {$each: ["sport", "soccer"]}}})

Update all documents with a name equal to article and add the "sport" and "soccer" tag to the list of tags in an descending order of views and keep only first three values of the array.

db.articles.updateMany({name: "article"}, {$push: {tags: {
	$each: [{views: 1, tag: "sport"}, {views: 20, tag: "soccer"}],
	$sort: {views: -1},
	$slice: 3
}}})

$pullAll

Removes all matching values from an array. Unlike the $pull operator that removes elements by specifying a query, $pullAll removes elements that match the listed values.

db.collection.update({query}, { $pullAll: { <field1>: [ <value1>, <value2> ... ], ... } })

Example of $pullAll

Update all documents with a name equal to article and remove the values 0, 1, 2 and 3 from the grades array.

db.articles.updateMany({name: "article"}, {$pullAll: {grades: [0, 1, 2, 3]}})

Modifiers update operators in MongoDB

$each

Modifies the $push and $addToSet operators to append multiple items for array updates.

db.collection.update({query}, 
	{ $push: { 
		<field>: { $each: [ <value1>, <value2> ... ] } 
	} }
)

Example of $each

Update all documents with a name equal to article and add the values 0, 1, 2 and 3 to the grades array.

db.articles.updateMany(
	{name: "article"}, 
	{$push: {grades: {$each: [0, 1, 2, 3]}}}
)

$position

Modifies the $push operator to specify the position in the array to add elements.

db.collection.update({query}, 
	{ $push: { 
		<field>: { 
			$each: [ <value1>, <value2> ... ],
			$position: <num>
		} 
	} }
)

Example of $position

Update all documents with a name equal to article and add the values 0, 1, 2 and 3 to the position 0 of the grades array.

db.articles.updateMany(
	{name: "article"}, 
	{$push: {grades: {
		$each: [0, 1, 2, 3],
		$position: 0
	}}}
)

$slice

Modifies the $push operator to limit the size of updated arrays.

db.collection.update({query}, 
	{ $push: { 
		<field>: { 
			$each: [ <value1>, <value2> ... ],
			$slice: <num>
		} 
	} }
)

Example of $slice

Update all documents with a name equal to article and add the values 0, 1, 2 and 3 to the grades array adn keep only 3 values in the array.

db.articles.updateMany(
	{name: "article"}, 
	{$push: {grades: {
		$each: [0, 1, 2, 3],
		$slice: 3
	}}}
)

$sort

Modifies the $push operator to reorder documents stored in an array. The sort specification takes -1 or 1 for simple values or { field: 1|-1 } in case of nested documents.

db.collection.update({query}, 
	{ $push: { 
		<field>: { 
			$each: [ <value1>, <value2> ... ],
			$slice: <sort specification>
		} 
	} }
)

Example of $sort

Update all documents with a name equal to article and add the values 1, 20, 3 and 16 to the grades array and keep only the 3 best grades.

db.articles.updateMany(
	{name: "article"}, 
	{$push: {grades: {
		$each: [0, 20, 2, 16],
		$sort: -1,
		$slice: 3
	}}}
)