Updating Documents
Update operations allow you to modify existing documents using MongoDB-style update operators.
updateOne
Updates the first matching document and returns the updated document (or null).
const updated = users.updateOne(
{ name: 'Alice' },
{ $set: { age: 29, city: 'Port Harcourt' } }
);
updateMany
Updates all matching documents and returns an array of the updated ones.
users.updateMany(
{ city: 'Lagos' },
{ $inc: { age: 1 } }
);
Supported Update Operators
| Operator | Description | Example |
|---|---|---|
$set | Set field values | { $set: { age: 30, active: true } } |
$inc | Increment a number | { $inc: { age: 1, score: 10 } } |
$push | Add item to an array | { $push: { tags: 'vip' } } |
$pull | Remove item from an array | { $pull: { tags: 'old' } } |
$unset | Remove a field | { $unset: { temporary: '' } } |
Combining Operators
users.updateOne(
{ name: 'Bob' },
{
$set: { lastLogin: new Date().toISOString() },
$inc: { loginCount: 1 },
$push: { tags: 'active' }
}
);
Async Versions
await users.updateOneAsync({ name: 'Alice' }, { $set: { age: 30 } });
await users.updateManyAsync({ city: 'Lagos' }, { $inc: { age: 1 } });
Next: Learn how to delete documents.