How to Use Upsert in MongoDB: Syntax and Examples
In MongoDB, use the
updateOne() or updateMany() methods with the upsert: true option to update a document if it exists or insert it if it does not. This lets you combine insert and update in one operation.Syntax
The upsert option is used with update methods like updateOne() or updateMany(). It tells MongoDB to insert a new document if no matching document is found.
- filter: Criteria to find the document to update.
- update: The changes to apply if the document exists.
- upsert: true: Insert if no document matches the filter.
javascript
db.collection.updateOne(
filter,
update,
{ upsert: true }
)Example
This example updates a user's age if the user exists, or inserts a new user document if not.
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'); const filter = { name: 'Alice' }; const update = { $set: { age: 30 } }; const options = { upsert: true }; const result = await users.updateOne(filter, update, options); console.log('Matched count:', result.matchedCount); console.log('Modified count:', result.modifiedCount); console.log('Upserted id:', result.upsertedId); } finally { await client.close(); } } run().catch(console.dir);
Output
Matched count: 0
Modified count: 0
Upserted id: ObjectId("...")
Common Pitfalls
Common mistakes when using upsert include:
- Forgetting to set
upsert: true, so no insert happens if no match is found. - Using update operators incorrectly, causing the entire document to be replaced instead of updated.
- Not handling the
upsertedIdto know if an insert occurred.
javascript
/* Wrong: Missing upsert option, no insert if no match */ db.collection.updateOne({ name: 'Bob' }, { $set: { age: 25 } }); /* Right: Include upsert option */ db.collection.updateOne({ name: 'Bob' }, { $set: { age: 25 } }, { upsert: true });
Quick Reference
Use this quick guide when working with upsert in MongoDB:
| Option | Description |
|---|---|
| filter | Criteria to find the document to update |
| update | Update operations to apply if document exists |
| upsert: true | Insert document if no match is found |
| updateOne() | Updates a single matching document |
| updateMany() | Updates multiple matching documents |
Key Takeaways
Always set upsert: true to insert if no matching document exists.
Use update operators like $set to modify fields without replacing the whole document.
Check the result's upsertedId to know if an insert happened.
updateOne() updates one document; updateMany() updates multiple documents.
Without upsert, update methods only modify existing documents.