用$设置(如果不是null mongodb)upsert
假设一个i有文档结构的集合。
{
uuid: "157071f4-2624-4c49-8735-bd345425a16b",
price: {
item1: 20,
item2: 30
}
}
现在,我想基于UUID来提高数据,使用类似
await Coll.findOneAndUpdate({uuid}, {$set: {[`price.${itemNo}`]: 40}, {upsert: true}}
我的问题是,即使在ItemNo已经存在的情况下,此处的$设置更新值也是如此。而且,如果我对查询进行检查,
{uuid, [`price.${itemNo}`]: {$exists: 0}}
那么它即使存在UUID,它也会因UpSert而创建一个新文档。
我的最终目标是如果不存在UUID,并且存在UUID,则如果存在UUID,则不要更新“ Price.item”的值,如果它也存在其他设置值。 $ SETONINSERT
之类的东西也不满足我只需要更新该值的要求。 提前致谢。
Suppose a I have a collection of document structure.
{
uuid: "157071f4-2624-4c49-8735-bd345425a16b",
price: {
item1: 20,
item2: 30
}
}
Now I want to upsert data based on uuid, using something like
await Coll.findOneAndUpdate({uuid}, {$set: {[`price.${itemNo}`]: 40}, {upsert: true}}
My issue is that $set here update values even in cases where itemNo already exists. And if I put a check on query, something like,
{uuid, [`price.${itemNo}`]: {$exists: 0}}
then it creates a new document due to upsert even if uuid exists.
My end goal is to achieve upsert if uuid doesn't exist and and if uuid exists then don't update the value for "price.item" if it also exists else set the value.
Some thing like $setOnInsert
also doesn't meet the requirement I only need to update the value.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
得到了解决方案。
我们可以通过首先定义我们的更新字段来实现这一目标:
然后做类似的事情:
Got the solution.
We can achieve this by first defining our update field something like:
Then doing something like: