← Back to MongoDB Course | Chapter 4: CRUD — Update | Lesson 1 of 7

updateOne()

updateOne changes the first document that matches a filter using update operators.

In this page:

  1. updateOne()
Syntax
javascript
db.collection_name.updateOne(
  filter,
  { $set: { field: new_value } }
)

updateOne()

db.collection.updateOne(filter, update) modifies at most one document. The update document must use operators such as $set, otherwise you get an error.

The result reports matchedCount and modifiedCount, which differ when the new value equals the old one.

Note: modifiedCount is 0 when the update changes nothing.

Example: updateOne()

bash
test> db.users.insertMany([{ _id: 1, name: "Ada", age: 36 }, { _id: 2, name: "Bob", age: 25 }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.users.updateOne({ _id: 1 }, { $set: { age: 37 } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.users.updateOne({ _id: 1 }, { $set: { age: 37 } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 0 }
test> db.users.updateOne({ _id: 99 }, { $set: { age: 1 } })
{ acknowledged: true, matchedCount: 0, modifiedCount: 0 }
test> db.users.find()
[
  { _id: 1, name: 'Ada', age: 37 },
  { _id: 2, name: 'Bob', age: 25 }
]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Passing a plain document instead of operators
  2. Assuming updateOne updates every match
  3. Ignoring matchedCount versus modifiedCount
Chapter Summary
  • updateOne changes the first match
  • Use operators like $set
  • matchedCount versus modifiedCount
  • Add a unique filter such as _id
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.