基于条件的更新

发布于 2025-01-31 20:01:22 字数 513 浏览 2 评论 0原文

await products.updateOne(
        {
          $and: [
            { name: { $eq: name } },
            { $expr: { $lt: ["$remaining", "$capacity"] } },
          ],
        },
        { $inc: { remaining: 1 } },
        { returnOriginal: false }
      );

而不是像So {$ expr:{$ lt:[“ $剩余”,“ $ apcation”}}}那样,而不是像SO {$ expr:{$ lt:{$ lt:[$ lt:争论?

这样做的原因是,我希望返回的matchCount在匹配name的情况下返回1。

await products.updateOne(
        {
          $and: [
            { name: { $eq: name } },
            { $expr: { $lt: ["$remaining", "$capacity"] } },
          ],
        },
        { $inc: { remaining: 1 } },
        { returnOriginal: false }
      );

Instead of having the condition in the query like so { $expr: { $lt: ["$remaining", "$capacity"] } }, is there a way to include this condition in the update argument?

The reason for this is so that I want the returned matchCount to return 1 if the name is matched.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

浪菊怪哟 2025-02-07 20:01:22

是的,如果您使用聚合更新使用Mongo 4.2+,则可以做到这一点。

db.collection.update({
  $and: [ //condition goes here
    {
      name: {
        $eq: "name"
      }
    },
    
  ],
  
},
[
  {
    "$set": { //conditional update
      "remaining": {
        "$switch": {
          "branches": [
            {
              case: {
                $lt: [ //condition to update
                  "$remaining",
                  "$capacity"
                ]
              },
              then: {
                $add: [ //true case
                  "$remaining",
                  1
                ]
              }
            }
          ],
          default: {
            $add: [ //if no match
              "$remaining",
              0
            ]
          }
        }
      }
    }
  }
])

Yes, you can do that if you use mongo 4.2+ using aggregate update.

db.collection.update({
  $and: [ //condition goes here
    {
      name: {
        $eq: "name"
      }
    },
    
  ],
  
},
[
  {
    "$set": { //conditional update
      "remaining": {
        "$switch": {
          "branches": [
            {
              case: {
                $lt: [ //condition to update
                  "$remaining",
                  "$capacity"
                ]
              },
              then: {
                $add: [ //true case
                  "$remaining",
                  1
                ]
              }
            }
          ],
          default: {
            $add: [ //if no match
              "$remaining",
              0
            ]
          }
        }
      }
    }
  }
])

playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文