Lesson 9 / 22

updateOne & updateMany

Modify existing documents that match a filter.

updateOne()

Updates the first document that matches the filter, using an update operator like $set.

db.users.updateOne(
  { name: "Grace Hopper" },
  { $set: { role: "admiral" } }
)

Output:

{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }

updateMany()

Same idea, but applies to every matching document.

db.users.updateMany(
  { role: "engineer" },
  { $set: { department: "platform" } }
)

Output:

{ acknowledged: true, matchedCount: 2, modifiedCount: 2 }

Be specific with your filter

A too-broad filter in updateMany() can silently change documents you didn't mean to touch — always test the filter with find() first.