Update MongoDB Field Using Value Of Another Field.

In this post, we will learn to Update the MongoDB field using the value of another field where we can use the set operator in combination with the expr operator only for referring the another field 


Update The Field

To update the value of one field by another field we have given an example below to explain how we can use the set operator along with the expr operator for referring another operator to update the field. For Same let’s take an example of the collection named as users as given below.

  "_id": ObjectId("12345"),
  "name": "John",
  "age": 30

And here if we want to add or update the age field for some value let it be making it twice it and for the same, we can use the update one() operator for the same and we have given an example below to execute or implement.

db. users.update(
  { _id: ObjectId("12345") },
  { $set: { age: { $multiply: [ "$age", 2 ] } } }

Here in the arguments given above first to update one is the query that identifies the document to be updated. In this case, we’re using the id field to match the document with an ID of “12345”.

Here we have the second argument is the update operation, to update which uses the set operator to set the value of the “age” field to the result of the multiply expression, which doubles the value of the “age” field.

Here we are using the multiply operator or expression to make the age double so for the same we are passing the age in the argument and getting it done. And after that, the result of the above code will be the result as the following output.

  "_id": ObjectId("12345"),
  "name": "John",
  "age": 60

As per the rule of updating if the same field occurs multiple times then the only first occurrence of the value will be updated to the value which is a]occurred first and the rest of the matching will be the same as it was.



To learn more about the Update MongoDB field using the value of another field visit:  by stack overflow.

To learn more about MongoDB and tutorial related to it visit: MongoDB Problems And Tutorials

Leave a Comment

%d bloggers like this: