0

In MongoDB, is it possible to update the value of a field using the value from another field?

sample doc in DB:

{
      "_id" : 1,
      "total":0,
      "amount1":100
   }

i wanted to update "total" = "amount1"+250;

expected result in DB:

{
   "_id" : 1,
   "total":350,
   "amount1":100
}

i tried with below query, but not worked.

db.getCollection('test').update({"_id" : 1)},
 {"$set":{"total":{ "$sum": { 250: "$amount1"}}}});

Please help me to solve this.

phani
  • 507
  • 2
  • 6
  • 18
  • @Ashh i think this is not duplicate https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field is about concat the strings – phani Nov 12 '19 at 05:57
  • Just use `$add` in place of `$concat`... `db.getCollection('test').update( { "_id": 1 }, [ { "$set": { "total": { "$add": ["$amount1", 250] }}} ] );` – Ashh Nov 12 '19 at 06:24
  • for this query im getting error message 'BSON field 'update.updates.u' is the wrong type 'array', expected type 'object'' – phani Nov 12 '19 at 07:18
  • What version of mongo are you using? I'm using 3.x and saw the same error. This worked for me: `db.test.aggregate( [ {"$addFields":{"total":{"$add":["$amount1",500]}}}, { "$out": "test" } ] )` – sudhanva Nov 12 '19 at 08:59
  • 3
    The syntax as shown by @Ashh is specific to MongoDB 4.2 and greater. Earlier versions will report an error much like you have stated. Actually [read the marked duplicate](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) which shows alternate **iterative** measures for reading an existing field and updating it. – Neil Lunn Nov 12 '19 at 09:49
  • 3
    The most highly voted answer does not clearly explain this ( which is why I have never voted for it ) but [it is clearly stated on another](https://stackoverflow.com/a/3976218/2313887) *"You cannot refer to the document itself in an update (yet). You'll need to iterate through the documents and update each document using a function"*. So if you have MongoDB 4.2, then yes this is a singular update statement. For anything else, it is not. And there is no other way to do that other than by iteration in that case. – Neil Lunn Nov 12 '19 at 09:51

0 Answers0