I have a mongoDB collection where I store time & costs saved. When the users enter the data for the first time the document kinda looks like this:
我有一个mongoDB集合,可以节省时间和成本。当用户第一次输入数据时,文档有点像这样:
{ "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:
这次用户输入:
- Time Saved 55
- money Saved 10
节省时间55
钱节省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中是否有内置功能可以帮助解决这个问题。
1 个解决方案
#1
2
You can do this by $inc operator. The $inc
operator increments a field by a specified value
您可以通过$ inc运营商执行此操作。 $ inc运算符按字段增加一个字段
For example in your case:
例如在你的情况下:
UserModel.update(
SomeFindCriteria,
{ $inc: { timeSaved: newTimeSaved, moneySaved: newMoneySaved } }
)
#1
2
You can do this by $inc operator. The $inc
operator increments a field by a specified value
您可以通过$ inc运营商执行此操作。 $ inc运算符按字段增加一个字段
For example in your case:
例如在你的情况下:
UserModel.update(
SomeFindCriteria,
{ $inc: { timeSaved: newTimeSaved, moneySaved: newMoneySaved } }
)