【问题标题】:Remove an object from a nested array with $pull and $[identifier] (mongoDB 3.6)使用 $pull 和 $[identifier] 从嵌套数组中删除对象(mongoDB 3.6)
【发布时间】:2018-02-09 21:38:50
【问题描述】:

MongoDB 3.6 允许对任何数组中的所有匹配元素执行复杂的数组操作——无论嵌套多深——Update Nested Arrays with $[identifier]

考虑以下关于survey 集合的文档:

{
    "_id": "5a7d86d8fac139e71b0b9f5b",
    "results": [
      {
        "items": [
          {
            "comments": [
              {
                "id" : "123456",
                "email": "user@email.com",
                "comment": "comment 1"
              }
            ]
          }
        ]
      }
    ]
  }

我正在尝试使用 $pull 和新的 $[<identifier>] 删除基于评论 id 的评论

我根据The update command 尝试了下面的command:

db.runCommand({
  update: "survey",
  updates: [
    {
      q: {},
      u: {
        $pull: {
          "results.$[].items.$[].comments.$[comment]": { "comment.id": { $eq: "123456" } }
        }
      },
      arrayFilters: [{ "comment.id": { $eq: "123456" } }]
    }
  ]
})

但它不起作用,因为 $pull 期望一个数组值: Cannot apply $pull to a non-array value

有什么帮助吗?谢谢。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    尝试positional all $[] 变体。

    类似

    db.runCommand({
      update: "survey",
      updates: [
        {
          q: {},
          u: {
            $pull: {
              "results.$[].items.$[].comments": { "id":  "123456" }
            }
          }
        }
      ]
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 2021-04-19
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      • 2021-07-03
      相关资源
      最近更新 更多