Update
Change fields of one or several documents with the update operators.
Change fields of one or several documents with updateOne, updateMany or replaceOne. Update operators and pipeline updates are MongoDB's.
Requirements
- A connection with a user that has
readWriteon the database.
Change fields
JavaScript
db.orders.updateOne({ customer: "Luis Gil" }, { $set: { status: "paid" }, $inc: { attempts: 1 } });Change several documents
JavaScript
db.orders.updateMany({ status: "pending" }, { $set: { notified: true } });Insert if it does not exist
JavaScript
db.counters.updateOne({ _id: "visits" }, { $inc: { value: 1 } }, { upsert: true });Check
The response carries matchedCount and modifiedCount. With upsert, it also carries upsertedId when the update
inserted a new document.
Common problems
- The update fails with
ConflictingUpdateOperators(40) because two operators touch the same path. - A counter that many clients update at once concentrates the load on that document's range.