Field update operators

Field update operators allow you to modify the value of a specified field in a document when certain conditions are met.

OperatorDescription
$setAssigns the value of a given field
$unsetDeletes the records of a field from a document
$incIncrements a given field’s value
$mulMultiplies a given field’s value by a specific value
$renameRenames a given field with another name
$minUpdates a particular field only when the specified value is lesser than the specified value
$maxUpdates a particular field only when the specified value is higher than the specified value
$currentDateSpecifies the current date and time as the value of a given field
$setOnInsertInserts elements into an array only if they don’t already exist

For the examples in this section, insert the following documents into the employees collection:

  1. db.employee.insertOne({
  2. name: 'John Doe',
  3. age: 35,
  4. email: 'johndoe@example.com',
  5. phone: '123-456-7890',
  6. address: {
  7. street: '123 Main St',
  8. city: 'Anytown',
  9. state: 'CA'
  10. },
  11. salary: 50000,
  12. jobTitle: 'Manager',
  13. startDate: new Date('2021-01-01'),
  14. endDate: null
  15. })

$set

The $set operator updates the value of a specified field and if the field does not exist, the $set operator creates a new field and adds it to the document.

Example: The below query is an example that updates the value of the city field in the address embedded document.

  1. db.employee.updateOne(
  2. { name: 'John Doe' },
  3. {
  4. $set: {
  5. 'address.city': 'New York',
  6. 'address.zip': '12345'
  7. }
  8. }
  9. )

The above query updates the value of the city field in the address embedded document and adds a new field zip to it.

This is the updated document:

  1. [
  2. {
  3. _id: ObjectId("640a603558955e0e2b57c00d"),
  4. name: 'John Doe',
  5. age: 35,
  6. email: 'johndoe@example.com',
  7. phone: '123-456-7890',
  8. address: {
  9. street: '123 Main St',
  10. city: 'New York',
  11. state: 'CA',
  12. zip: '12345'
  13. },
  14. salary: 50000,
  15. jobTitle: 'Manager',
  16. startDate: ISODate('2021-01-01T00:00:00.000Z'),
  17. endDate: null
  18. }
  19. ]

$unset

The $unset operator deletes the specified field from a document and if the field is not present, the $unset operator will not do anything.

Example: The below query deletes the zip field from the embedded document address.

  1. db.employee.updateOne({ name: 'John Doe' }, { $unset: { 'address.zip': '' } })

Below is the updated document, without the zip field:

  1. [
  2. {
  3. _id: ObjectId("640a603558955e0e2b57c00d"),
  4. name: 'John Doe',
  5. age: 35,
  6. email: 'johndoe@example.com',
  7. phone: '123-456-7890',
  8. address: {
  9. street: '123 Main St',
  10. city: 'New York',
  11. state: 'CA'
  12. },
  13. salary: 50000,
  14. jobTitle: 'Manager',
  15. startDate: ISODate('2021-01-01T00:00:00.000Z'),
  16. endDate: null
  17. }
  18. ]

$inc

The $inc operator increments the value of a given field by a specified amount. If the field is non-existent in the document, the $inc operator creates a new field and adds it to the document, setting the value to the specified increment amount.

Example: The below query increments the value of the age field by 1.

  1. db.employee.updateOne({ name: 'John Doe' }, { $inc: { age: 1 } })

The updated document looks like this:

  1. [
  2. {
  3. _id: ObjectId("640a603558955e0e2b57c00d"),
  4. name: 'John Doe',
  5. age: 36,
  6. email: 'johndoe@example.com',
  7. phone: '123-456-7890',
  8. address: {
  9. street: '123 Main St',
  10. city: 'New York',
  11. state: 'CA'
  12. },
  13. salary: 50000,
  14. jobTitle: 'Manager',
  15. startDate: ISODate('2021-01-01T00:00:00.000Z'),
  16. endDate: null
  17. }
  18. ]

$mul

The $mul operator multiplies the value of a given field by a specified amount. Similar to all most of the other field update operators, if the field is non-existent in the document, the $mul operator creates a new one and sets the value to 0.

Example: This example query multiplies the value of the salary field by 25%, represented as 1.25.

  1. db.employee.updateOne({ name: 'John Doe' }, { $mul: { salary: 1.25 } })

The updated record looks like this:

  1. [
  2. {
  3. _id: ObjectId("640a603558955e0e2b57c00d"),
  4. name: 'John Doe',
  5. age: 36,
  6. email: 'johndoe@example.com',
  7. phone: '123-456-7890',
  8. address: {
  9. street: '123 Main St',
  10. city: 'New York',
  11. state: 'CA'
  12. },
  13. salary: 62500,
  14. jobTitle: 'Manager',
  15. startDate: ISODate('2021-01-01T00:00:00.000Z'),
  16. endDate: null
  17. }
  18. ]

$rename

The $rename operator renames a given field to another name.

Example: The query below updates the employee collection and renames the jobTitle field to title.

  1. db.employee.updateOne({ name: 'John Doe' }, { $rename: { jobTitle: 'title' } })

The updated document looks like this:

  1. [
  2. {
  3. _id: ObjectId("640a603558955e0e2b57c00d"),
  4. name: 'John Doe',
  5. age: 36,
  6. email: 'johndoe@example.com',
  7. phone: '123-456-7890',
  8. address: {
  9. street: '123 Main St',
  10. city: 'New York',
  11. state: 'CA'
  12. },
  13. salary: 62500,
  14. startDate: ISODate('2021-01-01T00:00:00.000Z'),
  15. endDate: null,
  16. title: 'Manager'
  17. }
  18. ]

$min

The $min operator compares a specified value with the value of the given field and updates the field to the specified value if the specified value is less than the current value of the field.

Example: The below query updates the value of the age field to 30 as long as the current value is less than 30.

  1. db.employee.updateOne({ name: 'John Doe' }, { $min: { age: 30 } })

Since 30 is less than 36, the value of the age field is updated to 30. The updated document now looks like this:

  1. [
  2. {
  3. _id: ObjectId("640a603558955e0e2b57c00d"),
  4. name: 'John Doe',
  5. age: 30,
  6. email: 'johndoe@example.com',
  7. phone: '123-456-7890',
  8. address: {
  9. street: '123 Main St',
  10. city: 'New York',
  11. state: 'CA'
  12. },
  13. salary: 62500,
  14. startDate: ISODate('2021-01-01T00:00:00.000Z'),
  15. endDate: null,
  16. title: 'Manager'
  17. }
  18. ]

$max

The $max operator compares a specified value with the value of the given field and updates the field to the specified value if the specified value is greater than the current value of the field.

Example: The below query updates the value of the age field to 40 as long as the current value is greater than 40.

  1. db.employee.updateOne({ name: 'John Doe' }, { $max: { age: 40 } })

This is what the updated document looks like:

  1. [
  2. {
  3. _id: ObjectId("640a603558955e0e2b57c00d"),
  4. name: 'John Doe',
  5. age: 40,
  6. email: 'johndoe@example.com',
  7. phone: '123-456-7890',
  8. address: { street: '123 Main St', city: 'New York', state: 'CA' },
  9. salary: 62500,
  10. startDate: ISODate('2021-01-01T00:00:00.000Z'),
  11. endDate: null,
  12. height: 0,
  13. title: 'Manager'
  14. }
  15. ]

$currentDate

The $currentDate operator assigns the current date as the value of a given field. This can be as a date or timestamp.

Example: To update the startDate field with the current date, use the following query:

  1. db.employee.updateOne(
  2. { name: 'John Doe' },
  3. { $currentDate: { startDate: true } }
  4. )

This is the document after the update:

  1. [
  2. {
  3. _id: ObjectId("640a603558955e0e2b57c00d"),
  4. name: 'John Doe',
  5. age: 40,
  6. email: 'johndoe@example.com',
  7. phone: '123-456-7890',
  8. address: {
  9. street: '123 Main St',
  10. city: 'New York',
  11. state: 'CA'
  12. },
  13. salary: 62500,
  14. startDate: ISODate('2023-03-10T01:26:35.606Z'),
  15. endDate: null,
  16. height: 0,
  17. title: 'Manager'
  18. }
  19. ]

$setOnInsert

The $setOnInsert operator sets the value of a given field if the document is inserted into a collection during an upsert operation. If there is no insertion, the $setOnInsert operator does nothing.

Example: Let’s say you have a stocks collection that stores information about different stocks, and you want to update the stock information or add a new stock if it doesn’t exist. Here’s an example of how $SetOnInsert works differently from $set.

Using $set:

  1. db.stocks.update(
  2. { symbol: 'AAPL' },
  3. {
  4. $set: {
  5. price: 150,
  6. lastUpdate: new Date()
  7. }
  8. },
  9. { upsert: true }
  10. )

This query checks for a stock with the symbol “AAPL”. If it finds the stock, it updates the price and lastUpdate fields. If it doesn’t find the stock, it inserts a new document with the symbol, price, and lastUpdate fields.

Using $setOnInsert:

  1. db.stocks.update(
  2. { symbol: 'AAPL' },
  3. {
  4. $set: { price: 150 },
  5. $setOnInsert: {
  6. companyName: 'Apple Inc.',
  7. createdAt: new Date()
  8. }
  9. },
  10. { upsert: true }
  11. )

This query also checks for a stock with the symbol “AAPL”. If it finds the stock, it updates only the price field. If it doesn’t find the stock, it inserts a new document with the symbol, price, companyName, and createdAt fields. The companyName and createdAt fields are only added when a new document is inserted.

Comparing both examples, the $set operator updates or inserts the specified fields in both cases. On the other hand, the $setOnInsert operator sets the specified fields only when a new document is inserted, leaving existing documents unchanged.