Lesson 11 +10 XP

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

  • $set sets a field to a value.
  • $inc increments 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

MethodWhat 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.
  • $set changes values; $inc increments numbers.
  • { upsert: true } inserts if no document matches.