How to Use updateOne in MongoDB: Syntax and Examples
Use
updateOne in MongoDB to update a single document matching a filter. It takes a filter object to find the document and an update object specifying the changes, like { $set: { field: value } }. This method updates only the first matching document and returns the update result.Syntax
The updateOne method has this syntax:
- filter: Finds the document to update.
- update: Describes the changes to apply.
- options (optional): Additional settings like
upsert.
javascript
db.collection.updateOne(filter, update, options)
Example
This example updates the first user with the name "Alice" by changing her age to 30.
javascript
const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); try { await client.connect(); const db = client.db('testdb'); const users = db.collection('users'); // Update one document const result = await users.updateOne( { name: 'Alice' }, { $set: { age: 30 } } ); console.log('Matched documents:', result.matchedCount); console.log('Modified documents:', result.modifiedCount); } finally { await client.close(); } } run().catch(console.dir);
Output
Matched documents: 1
Modified documents: 1
Common Pitfalls
Common mistakes when using updateOne include:
- Forgetting to use update operators like
$set, which replaces the whole document if omitted. - Not specifying a filter, which can cause no documents to be updated.
- Expecting multiple documents to update;
updateOneonly updates the first match.
javascript
/* Wrong: Missing $set operator - replaces whole document */ db.collection.updateOne({ name: 'Alice' }, { age: 30 }); /* Right: Using $set to update only the age field */ db.collection.updateOne({ name: 'Alice' }, { $set: { age: 30 } });
Quick Reference
| Parameter | Description |
|---|---|
| filter | Object to find the document to update |
| update | Object describing the update operation (e.g., $set) |
| options | Optional settings like upsert (insert if no match) |
Key Takeaways
Always use update operators like $set to avoid replacing the whole document.
updateOne updates only the first document matching the filter.
Provide a clear filter to target the correct document.
Use options like upsert to insert if no document matches.
Check matchedCount and modifiedCount to verify the update result.