Skip to main content

How do you update a document in the DB?

To update a document in MongoDB, use updateOne() or updateMany() - depending on whether one document or several need to change.

An example of updating a single document:

js
db.users.updateOne( { name: "Alex" }, // the search condition { $set: { age: 26 } } // which fields to change )

How this works:

  • the first parameter is the filter MongoDB uses to find the right document
  • the second parameter is the $set operator, specifying which fields to update

If several documents need to be updated:

js
db.users.updateMany( { isActive: true }, { $set: { verified: true } } )

And if the whole document needs to be replaced:

js
db.users.replaceOne( { name: "Alex" }, { name: "Alex", age: 26, verified: true } )

In short: documents are updated via updateOne(), updateMany(), or replaceOne(), using operators like $set.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.