用$设置(如果不是null mongodb)upsert

发布于 2025-01-31 02:47:45 字数 611 浏览 2 评论 0原文

假设一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回眸一遍 2025-02-07 02:47:45

得到了解决方案。
我们可以通过首先定义我们的更新字段来实现这一目标:

let fieldName = `price.${itemNo}`

然后做类似的事情:

await Coll.findOneAndUpdate({
   uuid
},
[{
    $set: {
        [fieldName]: {
                $cond: [{
                    $or: [
                        {$ne: ["$price", null]},
                        {$ne: [`${fieldName}`, null]}
                    ]
                }, valueToBeSet, `${fieldName}`]
        }
    }
}], {upsert: true}
      

Got the solution.
We can achieve this by first defining our update field something like:

let fieldName = `price.${itemNo}`

Then doing something like:

await Coll.findOneAndUpdate({
   uuid
},
[{
    $set: {
        [fieldName]: {
                $cond: [{
                    $or: [
                        {$ne: ["$price", null]},
                        {$ne: [`${fieldName}`, null]}
                    ]
                }, valueToBeSet, `${fieldName}`]
        }
    }
}], {upsert: true}
      
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文