Updating Documents
Neuromancer sells out, then six copies arrive. You do not want to rewrite the whole book document just to change one number, and you certainly do not want two cashiers overwriting each other's counts. Update operators change exactly the fields you name.
The rule
Name the target, then say the change with an operator: $set, $inc, $push.
db.books.updateMany({ stock: { $lt: 5 } }, { $set: { reorder: true } })
// matchedCount: 2 (Neuromancer with 0, The Hobbit with 3)
db.books.updateOne({ _id: 2 }, { $inc: { stock: 6 } })
// { acknowledged: true, matchedCount: 1, modifiedCount: 1, upsertedId: null, ... }The common operators:
| Operator | Does | Example |
|---|---|---|
$set |
sets a field, creating it if missing | { $set: { price: 7.5 } } |
$unset |
removes a field | { $unset: { signed: "" } } |
$inc |
adds to a number (negative to subtract) | { $inc: { stock: -1 } } |
$push |
appends to an array | { $push: { genres: "space" } } |
$addToSet |
appends only if not already present | { $addToSet: { genres: "classic" } } |
$pull |
removes matching array elements | { $pull: { genres: "myth" } } |
- updateOne changes the first match; updateMany changes every match.
- Dotted paths work:
{ $set: { "publisher.country": "GB" } }. { upsert: true }as a third argument inserts a new document when nothing matches.- replaceOne(filter, newDoc) swaps the whole document, keeping only
_id. - The legacy
update()method is deprecated; use these.