3

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 ?

6
  • what is your MongoDB version ? Commented Feb 26, 2020 at 17:04
  • My MongoDB version is 3.6.15 Commented Feb 26, 2020 at 17:10
  • On 3.6 you don't have an option to direct update, You need to first read & then update !! For v4.2 you can do it in one call !! Anyway 3.6 is so old better upgrade your version asap.. Commented Feb 26, 2020 at 17:12
  • 1
    thanks, i'll try again with updated version Commented Feb 26, 2020 at 17:18
  • 1
    @whoami i tried your solution and it works in verison 4.2, thanks for your help Commented Feb 27, 2020 at 6:47

1 Answer 1

5

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] } } }])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.