代码之家  ›  专栏  ›  技术社区  ›  Gravity123

使用arrayFilters更新对象数组

  •  0
  • Gravity123  · 技术社区  · 3 年前

    我正试图通过应用过滤器来更新对象数组,但任何对象都不会发生更新,也不会出现错误。我希望根据我的过滤器更新所有对象。我使用的是MongoDB 6.0.8版本。

    查询:

    Buildings.update({}, {
      $inc: { "floors.$[index]": -1 }
    }, {
      arrayFilters: [ { "index": { $gt: 2 } } ]
    });
    

    数据:

    {
      _id: "YuzMQ5zKgktzrANsq",
      floors: [
        { index: 0 },
        { index: 1 },
        { index: 2 },
        { index: 3 },
        { index: 4 },
      ]
    }
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Yong Shun    3 年前

    你的 arrayFilters 和 $set 运算符不正确。由于您正在尝试更新对象中的字段,因此需要 dot notation with $[<identifier>] 。

    db.collection.update({},
    {
      $inc: {
        "floors.$[i].index": -1
      }
    },
    {
      arrayFilters: [
        {
          "i.index": {
            $gt: 2
          }
        }
      ]
    })
    

    Demo @ Mongo Playground