Updating Documents

1. Updating Single Document (updateOne())

ParamDescription
filterSelection criteria
updateOperator expression OR aggregation pipeline (4.2+)
optionsupsert, collation, hint, arrayFilters, writeConcern
returns{matchedCount, modifiedCount, upsertedId}
await db.users.updateOne({ _id: id }, { $set: { lastLogin: new Date() }, $inc: { loginCount: 1 } });

2. Updating Multiple Documents (updateMany())

AspectDetail
ScopeAll matching docs
AtomicityPer-document; not transactional unless in session
Retryable?No (multi=true ops are not retryable writes)

3. Replacing Document

MethodBehavior
replaceOne(filter, doc)Replace entire doc except _id
Constraintdoc must not contain update operators
UpsertSupported with {upsert: true}

4. Using $set Operator

BehaviorDetail
Sets valueCreates field if missing
NestedDot notation creates path
Array element$set: {"items.0.qty": 2}

5. Using $unset to Remove Fields

FormEffect
{$unset: {phone: ""}}Removes phone field
ValueIgnored (use "" by convention)
ArraysSets element to null; use $pull to remove

6. Incrementing Values ($inc)

FormEffect
{$inc: {qty: 1}}Atomic +1
{$inc: {qty: -5}}Decrement
TypeNumeric only; creates field if missing

7. Multiplying Values ($mul)

FormEffect
{$mul: {price: 1.1}}Multiply by 1.1
Missing fieldCreates with value 0

8. Renaming Fields ($rename)

FormEffect
{$rename: {old: "new"}}Rename top-level or dot path
ConflictsDrops target if it exists
ArraysCannot rename across array elements

9. Using $min and $max Operators

OperatorEffect
$minSet only if new value is less than current
$maxSet only if new value is greater than current
UseAtomic high/low watermark tracking

10. Setting on Insert ($setOnInsert)

AspectDetail
ActiveOnly when upsert results in insert
Use casecreatedAt, default fields
await db.users.updateOne(
  { email: "a@b.com" },
  { $set: { lastSeen: new Date() }, $setOnInsert: { createdAt: new Date(), role: "user" } },
  { upsert: true }
);

11. Using $currentDate Operator

FormEffect
{$currentDate: {updatedAt: true}}Sets server Date
{$currentDate: {ts: {$type: "timestamp"}}}Sets BSON Timestamp

12. Using findOneAndUpdate()

OptionDescription
returnDocument"before" (default) | "after"
projectionFields to return
sortChoose deterministic match
upsertInsert if no match
arrayFiltersConditional positional update

13. Using findOneAndReplace()

AspectDetail
BehaviorAtomic replace + return
ConstraintReplacement doc has no operators
OptionsSame as findOneAndUpdate

14. Handling Upsert Operations

AspectDetail
Filter equalityEquality fields are added to inserted doc
$setOnInsertInsert-only fields
Race conditionsCreate unique index on filter fields to prevent dupes
ResultupsertedId populated only when insert happened