updateOne()
updateOne changes the first document that matches a filter using update operators.
In this page:
Syntax
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()
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
- Passing a plain document instead of operators
- Assuming updateOne updates every match
- 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: