w3resource

Comprehensive Guide to db.collection.updateOne in MongoDB


Understanding db.collection.updateOne() in MongoDB

The db.collection.updateOne() method in MongoDB is used to update a single document in a collection that matches a given filter. It allows you to either modify specific fields of a document or replace the entire document based on the provided update criteria.

This method is ideal when you need to update only the first matching document rather than all documents in a collection.

Syntax:

db.collection.updateOne(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>,
     let: <document>,
     sort: <document>
   }
)

Parameters:

Name Type Description
filter Document Specifies the query criteria to match the document to update. Can include operators such as $eq, $lt, and $regex for flexible querying.
update Document Defines the modifications to apply. Can use update operators like $set, $unset, or $inc, or replace the entire document if no operators are used.
upsert Boolean (Optional) If true, creates a new document if no document matches the filter. Default is false.
writeConcern Document (Optional) Specifies the write concern for the operation, controlling the level of acknowledgment required from MongoDB. Example: { w: "majority", wtimeout: 5000 }.
collation Document (Optional) Configures how string comparisons are performed, such as case sensitivity or locale. Example: { locale: "en", strength: 2 }.
arrayFilters Array of Documents Defines filters for elements in arrays that need updating. Only applicable if the update document modifies array fields. Example: [ { "element.qty": { $gt: 10 } } ].
hint Document or String Specifies the index to use for the query, improving performance in certain scenarios. Example: { name: 1 } or "name_1".
let Document (Optional) Defines variables accessible in the filter and update expressions. Example: { priceLimit: 100 }, accessible as $$priceLimit.
sort Document (Optional) Specifies the order to apply when selecting the document to update, if multiple documents match the filter. Example: { age: -1 }.

Note:

  • All parameters, except filter and update, are optional.
  • Use the let parameter to simplify complex updates by referencing reusable variables in the query.

Returns

The method returns a document that contains:

  • matchedCount containing the number of matched documents
  • modifiedCount containing the number of modified documents
  • upsertedId containing the _id for the upserted document
  • upsertedCount containing the number of upserted documents
  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled

Behaviors

Updates a Single Document

db.collection.updateOne() finds the first document that matches the filter and applies the specified update modifications.

Update with an Update Operator Expressions Document

For the update specifications, the db.collection.updateOne() method can accept a document that only contains update operator expressions.

For example:

Code:

db.collection.updateOne(
   <query>,
   { $set: { status: "D" }, $inc: { quantity: 2 } },
   ...
)

Compatibility

You can use db.collection.updateOne() for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB

Example Usage

Basic Example

Code:

// Update a single document in the 'employees' collection
db.employees.updateOne(
  { name: "Comgall Izaiah" },     // Filter: Match document with name "Comgall Izaiah"
  { $set: { age: 31 } }           // Update: Set age to 31
)

Explanation:

  • The filter { name: "Comgall Izaiah" } selects the first document with name equal to "Comgall Izaiah."
  • The update operator $set modifies the age field to 31.
  • Only the first matching document is updated.

Using Multiple Update Operators

Code:

// Update multiple fields using $set and $inc
db.products.updateOne(
  { item: "Laptop" },             // Filter: Match document with item "Laptop"
  {
    $set: { inStock: true },      // Update: Set inStock to true
    $inc: { price: 100 }          // Update: Increase price by 100
  }
)

Explanation:

  • $set updates the inStock field to true.
  • $inc increases the price field by 100.
  • Both updates apply to the first matching document.

Replace Entire Document

Code:

// Replace the entire document
db.orders.updateOne(
  { orderId: 101 },               // Filter: Match document with orderId 101
  {
    orderId: 101,                 // Replacement document
    status: "Shipped",
    items: ["Laptop", "Mouse"]
  }
)

Explanation:

  • The document matching orderId: 101 is replaced entirely with the provided replacement document.
  • Fields not included in the replacement are removed.

Using the Upsert Option

Code:

// Insert a new document if no match is found
db.inventory.updateOne(
  { item: "Tablet" },             // Filter: Match document with item "Tablet"
  { $set: { qty: 50, price: 300 } }, // Update: Set qty and price
  { upsert: true }                // Option: Create document if not found
)

Explanation:

  • If a document matching the filter { item: "Tablet" } exists, it’s updated.
  • If no document matches, a new document is created with the specified fields.

Returned Acknowledgment

When db.collection.updateOne() executes, it returns a result object:

Code:

{
  "acknowledged": true,
  "matchedCount": 1,
  "modifiedCount": 1,
  "upsertedId": null
}

Fields:

  • acknowledged: Indicates if the operation was successful.
  • matchedCount: Number of documents that matched the filter.
  • modifiedCount: Number of documents that were modified.
  • upsertedId: The _id of the newly inserted document (only for upsert).

Error Scenarios

Invalid Update Operators

Code:

db.employees.updateOne(
  { name: "Silvestr Roland" }, 
  { age: 35 } // Error: Missing update operator
)

Error:

Code:

Update document requires update operators like $set

Reason:

  • The update document must use update operators such as $set unless replacing the entire document.

Missing Filter

Code:

db.employees.updateOne(
  {}, 
  { $set: { department: "HR" } }
)

Issue:

  • An empty filter ({}) may unintentionally match multiple documents.

Best Practices

1. Always Use Specific Filters:

  • Avoid empty filters ({}) to prevent unintended updates.

2. Validate Update Documents:

  • Ensure update documents use proper operators or are valid replacements.

3. Use Upserts with Care:

  • Be cautious when enabling upsert to avoid creating unwanted documents.

4. Test Updates Before Execution:

  • Use queries to confirm the filter matches the intended document(s).

Additional Examples

Incremental Updates

Code:

// Increment sales count
db.sales.updateOne(
  { product: "Phone" },           // Filter: Match product "Phone"
  { $inc: { salesCount: 1 } }     // Increment salesCount by 1
)

Unsetting a Field

Code:

// Remove a field from a document
db.employees.updateOne(
  { name: "Comgall Izaiah" },           // Filter: Match name "Comgall Izaiah"
  { $unset: { middleName: "" } }  // Remove the middleName field
)

Troubleshooting Tips

1. Check Filter Criteria

  • Ensure the filter matches the intended document(s) to avoid unexpected results.

2. Understand Operator Precedence

  • Combine multiple operators carefully to avoid conflicts or overwriting fields.

3. Monitor Performance for Large Collections

  • Index fields used in the filter to optimize update performance.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/mongodb/mongodb-db-collection-updateone.php