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

允我心安 提交于 2021-02-11 04:51:07

问题


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 ?


回答1:


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] } } }])


来源:https://stackoverflow.com/questions/60418883/how-to-update-a-number-field-using-another-number-field-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!