3.1 Field Update Operators
Key Takeaways
- updateOne() and updateMany() return an acknowledgment document containing matchedCount, modifiedCount, and upsertedId/upsertedCount.
- When upsert: true is specified, MongoDB creates a new document combining query filter equality fields with update operator directives if no document matches the filter.
- The $set operator creates or updates fields, while $unset removes fields entirely regardless of the specified placeholder value.
- Mathematical and comparison operators ($inc, $mul, $min, $max) execute atomic in-place modifications without requiring a round-trip read-modify-write cycle.
- $currentDate sets fields to the current date or BSON Timestamp, and $rename updates field keys atomically without moving data across collections.
3.1 Field Update Operators
In MongoDB, update operations modify existing documents in a collection without replacing the entire document structure. MongoDB provides field update operators that perform atomic, in-place modifications on specific fields. Understanding the mechanics of update methods, return documents, upsert behavior, and atomic field operators is essential for building scalable applications and passing the MongoDB Associate Developer Exam.
1. Core Update Methods
MongoDB provides two primary methods for updating documents in a collection:
db.collection.updateOne(filter, update, options): Modifies the first document that matches the query filter according to the natural storage order or specified index sort.db.collection.updateMany(filter, update, options): Modifies all documents in the collection that satisfy the query filter criteria.
Syntax Structure
db.collection.updateOne(
{ status: "PENDING", priority: { $gte: 3 } }, // Query filter
{
$set: { status: "IN_PROGRESS", assignedAt: new Date() },
$inc: { retryCount: 1 }
}, // Update document containing update operators
{
upsert: false,
writeConcern: { w: "majority", wtimeout: 5000 }
} // Options document
);
Critical Exam Rule: In modern MongoDB drivers and the
mongoshshell, the update argument must contain update operators (e.g.,$set,$inc) or an aggregation pipeline array. Supplying raw field-value pairs (e.g.,{ status: "IN_PROGRESS" }) without an update operator will throw a runtime error inupdateOne()andupdateMany().
2. Update Result & Return Objects
When updateOne() or updateMany() executes, MongoDB returns an acknowledgment document detailing the exact outcome of the operation:
{
acknowledged: true,
matchedCount: 5,
modifiedCount: 3,
upsertedId: null,
upsertedCount: 0
}
Anatomy of the Return Document
| Property | Type | Description & Exam Nuance |
|---|---|---|
acknowledged | Boolean | true if the write operation was executed with a recognized write concern; false if unacknowledged. |
matchedCount | Integer | The number of documents that matched the query filter criteria. |
modifiedCount | Integer | The number of existing documents actually modified. If a document matches the filter but the update sets a field to its already existing value, matchedCount is incremented, but modifiedCount remains 0. |
upsertedCount | Integer | The number of documents inserted as a result of an upsert operation (1 or 0). |
upsertedId | Any / ObjectId | The _id value of the newly inserted document if an upsert occurred; null if no document was inserted. |
matchedCount vs. modifiedCount Discrepancy
Consider a collection with a document: { _id: 1, status: "active", tier: "gold" }.
db.users.updateOne(
{ _id: 1 },
{ $set: { status: "active" } }
);
Result:
{
acknowledged: true,
matchedCount: 1,
modifiedCount: 0,
upsertedId: null,
upsertedCount: 0
}
Because the value of status was already "active", MongoDB detects that no byte-level changes are required. The document matched the query filter (matchedCount: 1), but the document was not altered (modifiedCount: 0). WiredTiger avoids unnecessary disk writes and oplog generation in this scenario.
3. Upsert Mechanics (upsert: true)
An upsert is a hybrid operation: if a document matching the query filter exists, MongoDB applies the update; if no matching document exists, MongoDB inserts a new document.
db.analytics.updateOne(
{ page: "/checkout", date: "2026-09-02" }, // Filter
{
$inc: { views: 1 },
$set: { lastAccessed: new Date() },
$setOnInsert: { createdAt: new Date(), initialReferrer: "direct" }
},
{ upsert: true } // Options
);
How MongoDB Constructs an Upserted Document
When upsert: true is triggered and no document matches the filter, MongoDB constructs the new document through the following process:
- Extracts Equality Clauses from the Filter: All top-level field equality conditions in the filter become initial fields in the new document (e.g.,
page: "/checkout",date: "2026-09-02"). - Applies Update Operator Modifications: Fields specified in operators like
$set,$inc, and$currentDateare evaluated and added. - Evaluates
$setOnInsert: Fields defined inside$setOnInsertare populated only upon insertion. If a matching document had been found,$setOnInsertdirectives would be completely ignored. - Generates
_id: If neither the query filter nor the update operators supply an_id, MongoDB generates a newObjectId.
4. Comprehensive Field Update Operators
MongoDB provides specialized field operators to manipulate values atomically within documents.
The Field Operators Matrix
| Operator | Syntax | Description | Behavior if Target Field Does Not Exist |
|---|---|---|---|
$set | { $set: { <field1>: <value1>, ... } } | Sets the value of a field. Replaces existing value or creates field. | Creates the field with the specified value. |
$unset | { $unset: { <field1>: "", ... } } | Deletes the specified field from the document. | Performs no operation (no error thrown). |
$inc | { $inc: { <field1>: <amount1>, ... } } | Increments or decrements a numeric field by a positive or negative number. | Creates the field and sets it to the increment amount. |
$min | { $min: { <field1>: <value1>, ... } } | Updates the field only if the specified value is less than the current value. | Creates the field with the specified value. |
$max | { $max: { <field1>: <value1>, ... } } | Updates the field only if the specified value is greater than the current value. | Creates the field with the specified value. |
$mul | { $mul: { <field1>: <number1>, ... } } | Multiplies the numeric value of a field by the specified multiplier. | Creates the field with a value of 0 (same numeric type as multiplier). |
$rename | { $rename: { <old_name>: <new_name> } } | Renames a field key atomically. | Performs no operation; does not error. |
$currentDate | { $currentDate: { <field1>: true / { $type: "date" / "timestamp" } } } | Sets the field value to the current date/time as a BSON Date or BSON Timestamp. | Creates the field with the current date/time. |
5. In-Depth Operator Analysis & Code Examples
5.1 $set and Dot Notation for Embedded Fields
$set replaces the value of a field with the specified value. It supports dot notation to reach deeply nested fields without overwriting adjacent sibling properties.
db.users.updateOne(
{ _id: 1001 },
{
$set: {
"profile.contact.email": "alex.dev@example.com",
"preferences.notifications.sms": false,
"accountStatus": "VERIFIED"
}
}
);
If profile.contact exists, only email is updated. If profile or contact does not exist, MongoDB creates the intermediate embedded subdocuments automatically.
5.2 $unset Field Deletion
$unset removes specified fields from documents. The value specified in the $unset expression (such as "" or 1) is ignored by MongoDB.
db.products.updateMany(
{ discontinued: true },
{
$unset: {
temporaryPromoCode: "",
flashSaleDiscount: 1
}
}
);
5.3 $inc and $mul for Mathematical Operations
$inc accepts positive numbers (to increment) or negative numbers (to decrement), including integers, longs, doubles, and Decimal128 values.
db.inventory.updateOne(
{ sku: "MDB-BOOK-01" },
{
$inc: { quantity: -5, reservedCount: 5 },
$mul: { price: 1.10 } // 10% price increase
}
);
Exam Trap:
$incand$mulcan only be applied to fields containing numeric types. Applying$incto a string or null field will throw aCannot apply $inc to a value of non-numeric typeerror.
5.4 $min and $max for Threshold Tracking
$min updates a field if the given value is smaller than the current field value. $max updates a field if the given value is greater than the current field value.
db.gameScores.updateOne(
{ playerId: "player_88" },
{
$max: { highScore: 9450 }, // Updated only if 9450 > current highScore
$min: { bestLapTimeSec: 42.18 }, // Updated only if 42.18 < current bestLapTimeSec
$currentDate: { lastPlayed: true }
},
{ upsert: true }
);
If playerId: "player_88" does not exist and an upsert occurs, MongoDB creates the document and sets highScore: 9450 and bestLapTimeSec: 42.18 because both $min and $max set the field when it is missing.
5.5 $rename for Atomic Key Migration
$rename alters field names within documents. It works on top-level fields as well as embedded subdocuments.
db.customers.updateMany(
{},
{
$rename: {
"cell": "mobileNumber",
"billing.zip": "billing.postalCode"
}
}
);
Key $rename Constraints:
- If the document already contains a field with
<new_name>,$renameremoves the existing field and assigns the value from<old_name>. $renamecannot move fields into or out of array elements.
5.6 $currentDate Type Options
$currentDate sets fields to the server's current date/time. It supports two representations:
- BSON Date (Default): Specified as
{ field: true }or{ field: { $type: "date" } }. - BSON Timestamp: Specified as
{ field: { $type: "timestamp" } }(used internally in oplogs and replication).
db.sessions.updateOne(
{ sessionId: "sess_abc123" },
{
$currentDate: {
lastActivity: true, // BSON Date
clusterSyncTime: { $type: "timestamp" } // BSON Timestamp
}
}
);
A collection contains the document: { _id: 101, username: "jdeveloper", score: 50, level: 1 }. A developer executes: db.users.updateOne({ _id: 101 }, { $set: { score: 50 }, $inc: { level: 0 } }); What is the returned acknowledgment document?
A developer runs the following command against an empty collection: db.logs.updateOne({ service: "auth", environment: "prod" }, { $inc: { count: 1 }, $setOnInsert: { createdDate: new Date("2026-09-01") }, $set: { lastActive: new Date("2026-09-02") } }, { upsert: true }); What document is created in the collection?
Which of the following field update operations will result in a runtime error when executed?
A collection has the document: { _id: 42, score: 75 }. What will be the value of score after executing: db.players.updateOne({ _id: 42 }, { $min: { score: 85 }, $max: { score: 90 } })?