w3resource

Update MongoDB Field Based on Another Field's Value

How to enable Pretty Print by default in MongoDB Shell?

To update a field in MongoDB using the value of another field in the same document, you can use the $set operator along with an aggregation pipeline in an update command. This approach allows MongoDB to refer to other fields within the document for calculations or transformations

Description:

In MongoDB, updating a field based on the value of another field can be done using an aggregation pipeline within the update command. This method is useful when you want to modify a field by referencing or manipulating another field's data, such as setting a field equal to another field's value or performing calculations between fields. This is particularly helpful for applications that need real-time updates based on existing document data.

Syntax:

To update a field using another field’s value, you can use the following syntax:

db.<collection>.updateOne(
  { <filter_conditions> },
  [
    { $set: { <field_to_update>: "<new_value_based_on_other_field>" } }
  ]
)

Explanation:

  • <collection>: The collection where you are performing the update.
  • <filter_conditions>: The conditions to match documents (e.g., { _id: <document_id> }).
  • <field_to_update>: The field that will be updated.
  • <new_value_based_on_other_field>: A reference to another field or a computed value based on other fields.

Example:

Suppose you have a products collection where each document has price and discount fields, and you want to calculate a new finalPrice by subtracting discount from price.

Code:

// Update the 'finalPrice' field in the 'products' collection
db.products.updateOne(
  // Match condition to find the document(s) you want to update
  { _id: ObjectId("64a8c1a5f0d7e7b3c2a3b4f7") },
  [
    {
      // Set 'finalPrice' field based on the value of 'price' and 'discount'
      $set: {
        // Calculate final price by subtracting 'discount' from 'price'
        finalPrice: { $subtract: ["$price", "$discount"] }
      }
    }
  ]
)

Explanation:

  • db.products.updateOne(...)
    Initiates an update operation in the products collection, targeting a specific document.
  • { _id: ObjectId(...) }
    This is the filter condition to locate the document. In this example, it filters by _id, but other filters can be applied based on your criteria.
  • $set
    The $set operator is used to update the finalPrice field.
  • finalPrice: { $subtract: ["$price", "$discount"] }
    Using $subtract, MongoDB calculates the finalPrice by subtracting the discount value from the price value. The $subtract operator within the aggregation pipeline allows referencing other fields in the document (indicated by the $ prefix).

This query updates finalPrice based on the values of price and discount within the same document. Using an aggregation pipeline for updates provides powerful capabilities for transforming and calculating field values dynamically.



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://w3resource.com/mongodb/snippets/how-to-update-a-mongodb-field-using-another-field-value.php