TExcelTAD
Home › MongoDB › MongoDB Update

MongoDB Update

Updating means finding documents with a filter and describing the change with an update document. The update document uses update operators such as $set or $inc, so you only send the fields that change, not the whole document.

Method Changes
updateOne(filter, update, options) the first matching document
updateMany(filter, update, options) every matching document
replaceOne(filter, replacement) swaps the whole first match for a new document (keeping _id)

updateOne with $set

$set assigns new values to fields, creating them if they don't exist:

mongosh · try it yourself
const r = db.products.updateOne(
  { _id: 6 },
  { $set: { price: 12.5, origin: 'Japan' } }
);
print(r.matchedCount, r.modifiedCount);
print(db.products.findOne({ _id: 6 }));
1 1
{
  _id: 6,
  name: 'Green Sencha',
  category: 'tea',
  price: 12.5,
  stock: 30,
  tags: [ 'green', 'loose-leaf' ],
  rating: 4.4,
  origin: 'Japan'
}

Fields you don't mention are left untouched.

updateMany

updateMany applies the same change to every match. The result tells you how many documents matched and how many really changed:

mongosh · try it yourself
const res = db.products.updateMany(
  { stock: 0 },
  { $set: { available: false } }
);
print(res);
print(db.products.find({ available: false }, { _id: 0, name: 1, stock: 1 }).toArray());
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 4,
  modifiedCount: 4,
  upsertedCount: 0
}
[
  { name: 'Colombia Supremo', stock: 0 },
  { name: 'Chamomile Calm', stock: 0 },
  { name: 'Milk Frother', stock: 0 },
  { name: 'Oat Cookies', stock: 0 }
]

modifiedCount can be smaller than matchedCount: if a document already has the value you set, MongoDB doesn't rewrite it.

mongosh · try it yourself
db.products.updateMany({ category: 'tea' }, { $set: { category: 'tea' } });
const again = db.products.updateMany({ category: 'tea' }, { $set: { category: 'tea' } });
print(again.matchedCount, again.modifiedCount);
4 0

Changing numbers with $inc

$inc adds to a number (use a negative value to subtract). It is atomic: two clients incrementing at the same time can never lose an update, which a read-modify-write in your application can:

mongosh · try it yourself
db.products.updateOne({ _id: 13 }, { $inc: { stock: 10 } });
db.products.updateOne({ _id: 13 }, { $inc: { stock: -3 } });
print(db.products.findOne({ _id: 13 }, { name: 1, stock: 1 }));
{ _id: 13, name: 'Gooseneck Kettle', stock: 11 }

Updating nested fields

Use dot notation inside $set to change one field of an embedded document without replacing the whole sub-document:

mongosh · try it yourself
db.customers.updateOne({ _id: 4 }, { $set: { 'address.city': 'Hillsboro' } });
print(db.customers.findOne({ _id: 4 }, { name: 1, address: 1 }));

// Compare: setting the whole sub-document replaces it
db.customers.updateOne({ _id: 12 }, { $set: { address: { city: 'Tacoma' } } });
print(db.customers.findOne({ _id: 12 }, { name: 1, address: 1 }));
{
  _id: 4,
  name: 'Linus Torvalds',
  address: { city: 'Hillsboro', country: 'USA' }
}
{ _id: 12, name: 'Radia Perlman', address: { city: 'Tacoma' } }

Customer 12 lost the country field, because $set: { address: … } replaced the whole embedded document.

replaceOne

replaceOne throws away every field except _id and stores the new document. The replacement must not contain operators:

mongosh · try it yourself
db.customers.replaceOne(
  { _id: 8 },
  { name: 'Donald E. Knuth', tier: 'gold', email: 'don@example.com' }
);
print(db.customers.findOne({ _id: 8 }));
{
  _id: 8,
  name: 'Donald E. Knuth',
  tier: 'gold',
  email: 'don@example.com'
}

When nothing matches

An update whose filter matches nothing is not an error. It just reports matchedCount: 0. (To insert a document in that case, use an upsert.)

mongosh · try it yourself
print(db.products.updateOne({ _id: 999 }, { $set: { price: 1 } }));
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 0
}

Common mistakes

  • Forgetting $set. updateOne(filter, { price: 10 }) throws Update document requires atomic operators. Use { $set: { price: 10 } }, or replaceOne if you really want to replace the document.
  • Using updateOne when you meant updateMany. Only the first match changes; check matchedCount.
  • Trying to change _id. It is immutable. Insert a new document and delete the old one instead.

Test yourself

What does updateMany({ category: 'tea' }, { $set: { onSale: true } }) do?

  1. Replaces every tea document with { onSale: true }
  2. Adds or sets onSale: true on every tea product, keeping other fields
  3. Updates only the first tea product
  4. Fails because onSale doesn't exist

Why is $inc safer than reading a value, adding 1 in your app and writing it back?

  1. It is shorter
  2. The server applies it atomically, so concurrent increments aren't lost
  3. It also creates an index
  4. It works on strings

A document has address: { city: 'Oslo', country: 'Norway' }. After $set: { address: { city: 'Bergen' } }, what is address?

  1. { city: 'Bergen', country: 'Norway' }
  2. { city: 'Bergen' }
  3. Unchanged
  4. An error