MongoDB从对象数组中的数组中删除项

jer*_*son 8 arrays mongodb mongodb-query subdocument

我有一个看起来像这样的文档:

{
  "_id" : ObjectId("56fea43a571332cc97e06d9c"),
  "sections" : [
    {
      "_id" : ObjectId("56fea43a571332cc97e06d9e"),
      "registered" : [
        "123",
        "e3d65a4e-2552-4995-ac5a-3c5180258d87"
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想删除只有特定部分'e3d65a4e-2552-4995-ac5a-3c5180258d87'registered数组中的._id'56fea43a571332cc97e06d9e'

我目前的尝试是这样的,但它只是返回未修改的原始文档.

db.test.findOneAndUpdate(
{
  $and: [
    {'sections._id': ObjectId('56fea43a571332cc97e06d9e')},
    {'sections.registered': 'e3d65a4e-2552-4995-ac5a-3c5180258d87'}
  ]
},
{
  $pull: {
    $and: [
      {'sections._id': ObjectId('56fea43a571332cc97e06d9e')},
      {'sections.registered': 'e3d65a4e-2552-4995-ac5a-3c5180258d87'}
    ]
  }
})
Run Code Online (Sandbox Code Playgroud)

我已经查看了$pull,但我似乎无法弄清楚如何使它适用于包含另一个数组的嵌套对象数组.这些$pull例子似乎只涉及一个嵌套级别.如何删除从匹配条目registered的项目阵列中sections与阵列_id,我的供应?

sty*_*ane 6

您需要使用位置$更新运算符从数组中删除元素。您需要这样做是因为“节”是子文档的数组。

db.test.findOneAndUpdate(
    { "sections._id" : ObjectId("56fea43a571332cc97e06d9e") }, 
    { "$pull": { "sections.$.registered": "e3d65a4e-2552-4995-ac5a-3c5180258d87" } } 
)
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我实际上像人类一样阅读了“$”的文档。这是有道理的。感谢您的帮助。 (3认同)