【问题标题】:How to use two operators in one query with arrayFilters condition in MongoDB / Node.js?如何在 MongoDB / Node.js 中使用 arrayFilters 条件在一个查询中使用两个运算符?
【发布时间】:2023-01-17 18:15:34
【问题描述】:

我正在尝试更新现金字段(增量)和积极的嵌套文档中的字段(从真到假)。我正在使用 node.js 和 mongodb。

我有这个文件:

[
  {
    "name": "Josh",
    "personId": "1234",
    "cash": 100,
    "events": [ {"type": "event1", "active": true }, {"type": "event2", "active": true}]
  },
  {
    "name": "Angelo",
    "personId": "7890",
    "cash": 50,
    "events": [ {"type": "event1", "active": true }, {"type": "event2", "active": true}]
  }
]

这是我的查询

db.collection("users").updateOne({ personId: personId }, { $inc: { cash: 100 }, $set: {"events.$[elem].active": false }, arrayFilters: [{ "elem.type": "event1" }] })

但我收到“未捕获的 MongoServerError MongoServerError:在路径‘events.$[elem].status”中找不到标识符‘elem’的数组过滤器”。可能与我的语法有关。

我可以更新嵌套字段“活动”这个就好了没有增量:

db.collection("users").updateOne({ personId: personId}, { $set: {"events.$[elem].active": false }}, {arrayFilters: [{ "elem.type": "event1" }] })

如何将 $inc 和 $set 与 arrayFilters 条件一起使用 (arrayFilters 仅适用于 $set)?

【问题讨论】:

    标签: node.js database mongodb


    【解决方案1】:

    你的语法是错误的。检查 docs 的内容:

    db.collection.updateMany(
       { <query conditions> },
       { <update operator>: { "<array>.$[<identifier>]" : value } },
       { arrayFilters: [ { <identifier>: <condition> } ] }
    )
    

    您可以看到三个对象:query、update 和 arrayFilters。而你只有两个。

    所以你可以使用:

    db.collection.update({
      personId: "1234"
    },
    {
      $inc: {
        cash: 100
      },
      $set: {
        "events.$[elem].active": false
      },
      
    },
    {
      arrayFilters: [
        {
          "elem.type": "event1"
        }
      ]
    })
    

    例子here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 2020-09-09
      • 2018-12-28
      • 1970-01-01
      相关资源
      最近更新 更多