MongoDB 从对象数组中的数组中删除一个项目

MongoDB remove an item from an array inside an array of objects

我有一个如下所示的文档:

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

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

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

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'}
    ]
  }
})

我查看了 $pull,但我似乎无法弄清楚如何让它在包含另一个数组的嵌套对象数组上工作。 $pull 示例似乎都只处理一层嵌套。如何使用我提供的 _idsections 数组中的项目的 registered 数组中删除匹配条目?

您需要使用位置 $ 更新运算符从数组中删除元素。你需要这个是因为 "sections" 是一个子文档数组。

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