MongoDB从对象数组内的数组中删除一个项目 [英] MongoDB remove an item from an array inside an array of objects

查看:18
本文介绍了MongoDB从对象数组内的数组中删除一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a document that looks like this:

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

我想删除 onlyregistered 数组中的 'e3d65a4e-2552-4995-ac5a-3c5180258d87''56fea43a571332cc97e06d9e'_id 部分.

I'd like to remove the 'e3d65a4e-2552-4995-ac5a-3c5180258d87' in the registered array of only the specific section with the _id of '56fea43a571332cc97e06d9e'.

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

My current attempt is something like this, but it just returns the original document unmodified.

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 数组中删除匹配的条目?

I've looked in to $pull, but I can't seem to figure out how to make it work on an array of nested objects containing another array. The $pull examples all seem to deal with only one level of nesting. How do I remove the matching entry from the registered array of the item in the sections array with the _id that I supply?

推荐答案

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

You need to use the positional $ update operator to remove the element from your array. You need this is because "sections" is an array of sub-documents.

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

这篇关于MongoDB从对象数组内的数组中删除一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆