TExcelTAD
Home › MongoDB › MongoDB Update Operators

MongoDB Update Operators

The second argument of updateOne and updateMany is an update document made of update operators. Each operator takes a document of field: value pairs, and you can combine several operators in one update.

Field operators

Operator Effect
$set set a field to a value (creates it if missing)
$unset remove a field
$inc add a number to a field (creates it with that number if missing)
$mul multiply a field by a number
$rename rename a field
$min set the field only if the new value is smaller
$max set the field only if the new value is larger
$currentDate set the field to the current date/time
$setOnInsert set fields only when an upsert inserts a new document (Upserts)

$set and $unset

mongosh · try it yourself
db.products.updateOne({ _id: 20 }, {
  $set: { color: 'forest green', 'specs.capacityMl': 350 },
  $unset: { rating: '' }
});
print(db.products.findOne({ _id: 20 }));
{
  _id: 20,
  name: 'Travel Mug',
  category: 'merch',
  price: 16,
  stock: 25,
  tags: [ 'reusable' ],
  color: 'forest green',
  specs: { capacityMl: 350 }
}

The value given to $unset doesn't matter; '' or 1 are the usual choices. $set with a dotted path created the specs sub-document because it didn't exist.

$inc and $mul

mongosh · try it yourself
// sell 3 kettles, then raise all equipment prices by 10%
db.products.updateOne({ _id: 13 }, { $inc: { stock: -3, sold: 3 } });
db.products.updateMany({ category: 'equipment' }, { $mul: { price: 1.1 } });
db.products.find({ category: 'equipment' }, { _id: 0, name: 1, price: 1, stock: 1, sold: 1 })
  .limit(4).forEach(p => print(p));
{ name: 'Pour-Over Dripper', price: 31.900000000000002, stock: 15 }
{ name: 'French Press', price: 38.5, stock: 9 }
{ name: 'Burr Grinder', price: 97.9, stock: 6 }
{ name: 'Gooseneck Kettle', price: 64.9, stock: 1, sold: 3 }

The new sold field was created by $inc. And because prices are doubles, 29 * 1.1 isn't exactly 31.9, a good reason to store money as Decimal128 or whole cents (see Documents and BSON Types).

$rename

mongosh · try it yourself
db.customers.updateMany({}, { $rename: { tier: 'loyaltyTier' } });
print(db.customers.findOne({ _id: 3 }, { name: 1, tier: 1, loyaltyTier: 1 }));
{ _id: 3, name: 'Grace Hopper', loyaltyTier: 'gold' }

$min and $max

These are perfect for keeping records such as "lowest price ever" or "highest score": the update is only applied if it improves the stored value.

mongosh · try it yourself
db.records.insertOne({ _id: 'espresso', lowestPrice: 24.5, bestRating: 4.7 });

db.records.updateOne({ _id: 'espresso' }, { $min: { lowestPrice: 22 }, $max: { bestRating: 4.5 } });
print(db.records.findOne());

db.records.updateOne({ _id: 'espresso' }, { $min: { lowestPrice: 23 }, $max: { bestRating: 4.9 } });
print(db.records.findOne());
{ _id: 'espresso', lowestPrice: 22, bestRating: 4.7 }
{ _id: 'espresso', lowestPrice: 22, bestRating: 4.9 }

Note: The collection is called records because db.stats is already taken: db.stats() is a database method. For a collection whose name clashes with a method, use db.getCollection('stats').

In the first update the price dropped (22 < 24.5) but the rating 4.5 was worse than 4.7, so it was ignored. In the second it was the other way round.

$currentDate

$currentDate stores the server's clock time, which is handy for updatedAt fields. The value changes on every run, so this example prints only its type:

mongosh · try it yourself
db.orders.updateOne({ _id: 1015 }, { $set: { status: 'shipped' }, $currentDate: { updatedAt: true } });
const o = db.orders.findOne({ _id: 1015 });
print(o.status, o.updatedAt instanceof Date);
shipped true

One operator per field

A single update can't modify the same field with two operators. MongoDB rejects it as a conflict:

mongosh · try it yourself
try {
  db.products.updateOne({ _id: 1 }, { $set: { stock: 0 }, $inc: { stock: 5 } });
} catch (err) {
  print(err.message);
}
Updating the path 'stock' would create a conflict at 'stock'

Updates with an aggregation pipeline

Instead of an update document, you can pass an array of aggregation stages ($set, $unset, $project, $replaceWith, …). This lets a new value be computed from other fields of the same document, which the classic operators can't do:

mongosh · try it yourself
db.products.updateMany({ category: 'coffee' }, [
  { $set: { stockValue: { $multiply: ['$price', '$stock'] } } }
]);
db.products.find({ category: 'coffee' }, { _id: 0, name: 1, stockValue: 1 }).forEach(p => print(p.name, p.stockValue));
Espresso Beans 980
House Blend 1170
Ethiopia Yirgacheffe 324
Colombia Supremo 0
Decaf Night Owl 429

Inside a pipeline '$price' means "the value of the field price". In a classic update document, the same string would just be stored as text.

Test yourself

A document has best: 80. What is best after { $max: { best: 75 } }?

  1. 75
  2. 80
  3. 155
  4. The field is removed

What does { $inc: { views: 1 } } do when views doesn't exist?

  1. Throws an error
  2. Creates views: 1
  3. Creates views: 0
  4. Does nothing

How do you set total to price * qty from the same document?

  1. { $set: { total: '$price * $qty' } }
  2. { $mul: { total: ['$price', '$qty'] } }
  3. An update pipeline: [{ $set: { total: { $multiply: ['$price', '$qty'] } } }]
  4. It is impossible in MongoDB