Faruk Yazici
Faruk Yazici

Reputation: 93

how to update a number field using another number field in MongoDB

Can MongoDB allow updating a number field using another number field in same document ? Let say I have a document like below :

{
   "_id" : "1",
   "a" : 2,
   "b" : 3
}

a and b fields are number fields(decimal,int...) my goal is update field b using field a How can I set b like b = 2*a. Is this possible ?

Upvotes: 3

Views: 2714

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Note :

  1. On v3.6 you don't have an option for direct update, You need to first read & process in code, then update.
  2. For v>= 4.2 you can do it in one call as .update() will accept aggregation pipeline & things can be done in one update call to DB. You can try this :

Query :

db.getCollection('collectionName').update({}, [{ $set: { b: { $multiply: ["$a", 2] } } }])

Upvotes: 5

Related Questions