Loading lessons...
Update Documents
Update Documents
To change existing documents, use updateOne() (first match) or updateMany() (all matches). Updates use update operators like $set and $inc.
updateOne() - update the first match
db.posts.updateOne(
{ title: "Post Title 1" },
{ $set: { likes: 2 } }
)
The first argument is the query (which document), the second is the update (the changes). This sets likes to 2 on the first document with that title.
$set and $inc
$setsets a field to a value.$incincrements a numeric field:
// Add 1 to likes on every document
db.posts.updateMany({}, { $inc: { likes: 1 } })
updateMany({}, ...) with an empty query applies to all documents.
Upsert: insert if not found
With the third argument { upsert: true }, if the query matches nothing, MongoDB inserts the provided document instead:
db.posts.updateOne(
{ title: "Post Title 5" },
{ $set: { title: "Post Title 5", body: "Body of post.", category: "Event", likes: 5 } },
{ upsert: true }
)
Method summary
| Method | What it updates |
|---|---|
| updateOne() | First matching document |
| updateMany() | All matching documents |
TL;DR
updateOne(query, update)updates the first match.updateMany(query, update)updates all matches.$setchanges values;$incincrements numbers.{ upsert: true }inserts if no document matches.