Multiply field by value in Mongodb

后端 未结 4 894
旧时难觅i
旧时难觅i 2020-12-01 03:15

I\'ve been looking for a way to create an update statement that will take an existing numeric field and modify it using an expression. For example, if I have a field called

4条回答
  •  半阙折子戏
    2020-12-01 03:17

    Well, this is possible with an atomic operation as $set.

    You have several options :

    • use the eval() solution proposed by pingw33n
    • retrieve the document you want to modify to get the current value and modify it with a set
    • if you have a high operation rate, you might want to be sure the focument has not changed during you fetch its value (using the previous solution) so you might want to use a findAndModify (see this page to get inspired on how to do it) operation.

    It really depends on your context : with a very low pressure on the db, I'd go for the solution of pingw33n. With a very high operation rate, I'd use the third solution.

提交回复
热议问题