简体   繁体   English

MongoDB / Mongoose-通过执行加法更新文档中的数字

[英]MongoDB/Mongoose - Update a number in document by performing Addition

I have a mongoDB collection where I store time & costs saved. 我有一个mongoDB集合,用于存储节省的时间和成本。 When the users enter the data for the first time the document kinda looks like this: 当用户第一次输入数据时 ,文档有点像这样:

{ "fullName" : "john smith",
  "company" : "xyz",
  "email" : "john.smith@xyz.com",
  "timeSaved" : 50 //this is in minutes
  "moneySaved" : 10 //this is in dollars
}

Now when the user enters the data again I find if a document already exists for this user and if it does I get it. 现在,当用户再次输入数据时,我发现该用户是否已经存在文档,如果可以,我会得到它。

This time the user entered: 这次用户输入:

  1. Time Saved 55 节省时间55
  2. money Saved 10 省钱10

I want to add the new values to the existing values. 我想新值添加到现有值。 So after the documents shows this: 所以在文件显示之后:

"timeSaved" : 105 // old 50 + new 55
"moneySaved" : 20 // old 10 + new 10

Whats the best way to achieve this. 什么是实现这一目标的最佳方法。 Is there an inbuilt function in mongodb/mongoose that can help with this. mongodb / mongoose中是否有一个内置函数可以对此提供帮助。

You can do this by $inc operator. 您可以通过$ inc运算符执行此操作。 The $inc operator increments a field by a specified value $inc运算符使字段增加指定值

For example in your case: 例如,在您的情况下:

UserModel.update(
    SomeFindCriteria,
   { $inc: { timeSaved: newTimeSaved, moneySaved: newMoneySaved } }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM