MongoDB Update Operations: 5 Quick Ways to Modify Documents

MongoDB is a popular document - oriented database, and update operations are a very common requirement in daily use. This article will introduce 5 of the most practical MongoDB update operation methods for beginners, covering scenarios such as modifying fields, increasing/decreasing values, array operations, complete replacement, and batch updates, so that you can quickly master the core skills of document modification.

1. Method 1: Use $set to modify fields (add/modify fields)

Function: $set can modify the value of an existing field and can also add a new field to the document. Other unspecified fields will be retained.
Applicable scenario: When you need to update some fields (such as modifying the email and age in user information) or add new attributes to a document.

Syntax:

db.collection_name.updateOne(
  { query conditions },  // Filter the document to be updated (required)
  { $set: { field1: new value, field2: new value, ... } }  // Fields to be modified/added (required)
)

Example:
Suppose there is the following document in the users collection:

{
  _id: 1,
  name: "Alice",
  age: 25,
  hobbies: ["reading", "coding"]
}

Now, we want to change Alice’s age to 26 and add a new field city (city):

db.users.updateOne(
  { name: "Alice" },  // Query condition: document with name "Alice"
  { $set: { age: 26, city: "Beijing" } }  // Modify age and add city field
)

After operation:

{
  _id: 1,
  name: "Alice",
  age: 26,
  hobbies: ["reading", "coding"],
  city: "Beijing"  // Newly added field
}

Note: If the field does not exist, $set will automatically create it; if the field already exists, it will directly overwrite the old value.

2. Method 2: Use $inc to increase/decrease values (numeric fields)

Function: $inc is used to perform increment/decrement operations on numeric fields (positive numbers increase, negative numbers decrease).
Applicable scenario: Scenarios that require dynamic adjustment of values, such as counters, points, ratings, etc.

Syntax:

db.collection_name.updateOne(
  { query conditions },
  { $inc: { numeric_field: increment_value } }  // When the increment value is positive, it increases; when it is negative, it decreases
)

Example:
Suppose Alice’s score is 80, and now we want to increase it by 10 points:

db.users.updateOne(
  { name: "Alice" },
  { $inc: { score: 10 } }  // score increases by 10
)

After operation:

{
  _id: 1,
  name: "Alice",
  age: 26,
  hobbies: ["reading", "coding"],
  score: 90  // Original 80 + 10 = 90
}

Note: If the numeric field does not exist, $inc will throw an error (you need to ensure that the field exists or initialize it as a number first); if the increment value is 0, the document will not be modified.

3. Method 3: Use $push to add elements to an array

Function: $push is used to append new elements to an array field while retaining the original array elements.
Applicable scenario: Adding new content to array fields such as lists, comments, tags (such as article comments, product tags).

Syntax:

db.collection_name.updateOne(
  { query conditions },
  { $push: { array_field: new_element } }  // Add new elements to the end of the array
)

Example:
Suppose Alice’s hobbies array needs to add “swimming”:

db.users.updateOne(
  { name: "Alice" },
  { $push: { hobbies: "swimming" } }  // New "swimming" added to the end of the array
)

After operation:

{
  _id: 1,
  name: "Alice",
  age: 26,
  hobbies: ["reading", "coding", "swimming"],  // Original array + new element
  city: "Beijing"
}

Note: If the array does not exist, $push will automatically create the array and add elements to it; to avoid duplicate elements, you can use $addToSet (advanced content later).

4. Method 4: Use replaceOne to completely replace a document

Function: replaceOne replaces the first document that meets the conditions with a brand - new document. Only the _id field is retained (if the new document does not contain _id, MongoDB will automatically generate a new one).
Applicable scenario: When the document structure needs to be completely replaced (such as when the fields of the old document are outdated and need to be rewritten completely).

Syntax:

db.collection_name.replaceOne(
  { query conditions },
  { new document content }  // Must contain fields; if you need to retain the original fields, you need to specify them explicitly
)

Example:
Completely replace Alice’s document with a new structure (retain name and _id, add gender and age):

db.users.replaceOne(
  { name: "Alice" },
  { _id: 1, name: "Alice", gender: "female", age: 27 }  // New document
)

After operation:

{
  _id: 1,  // Original _id is retained
  name: "Alice",
  gender: "female",
  age: 27  // All original fields are completely replaced
}

Note: If the new document does not contain _id, MongoDB will generate a new _id, and the original document’s _id will be permanently lost; it is recommended to confirm the new document structure before operation to avoid data loss.

5. Method 5: Use updateMany for batch updates

Function: updateMany performs update operations on all documents that meet the conditions, which is more efficient than looping for single - item updates.
Applicable scenario: Batch modification of a large amount of data (such as changing all “pending” orders to “processed”).

Syntax:

db.collection_name.updateMany(
  { query conditions },  // Conditions to match multiple documents
  { update operation }  // The same syntax as updateOne
)

Example:
Increase the age of all users with age > 25 by 5 years:

db.users.updateMany(
  { age: { $gt: 25 } },  // Query condition: age greater than 25
  { $inc: { age: 5 } }   // age of each matching document increases by 5
)

Result: All users meeting the conditions (assuming 3 users have age > 25) have their age increased by 5.

Note: After execution, it returns matchedCount (number of matched documents) and modifiedCount (number of actually modified documents), which can be used to verify whether the update is successful.

Summary

MongoDB update operations are flexible and diverse. Beginners can choose the appropriate method according to their needs:
- Modify part of the fields: Use $set (most commonly used);
- Increase/decrease values: Use $inc;
- Add elements to arrays: Use $push;
- Completely replace: Use replaceOne;
- Batch modification: Use updateMany.

Important reminder: Be sure to confirm the query conditions (where) before updating to avoid mistakenly updating all table data; if you modify important data, it is recommended to back up first or test the query condition range. With these 5 methods, you can cover 80% of the daily update scenarios. You can further learn more complex array operations such as $addToSet and $pull in the future.

Xiaoye