MongoDB $ pull从带有过滤器的数组

时间:2018-07-02 11:50:12

标签: mongodb mongoose

我有用户集合:

[
  {
    _id: '5b3935c2d4850aa2d9f0ae25',
    feedBucket: [
      {
        _id: '2a3535c2d4852ba2d9f0ae52',
        createdAt: '2018-06-30 21:52:22.681'
      },
      {
        _id: '9f342c2d4852ba2d9f0ae52',
        createdAt: '2018-06-30 21:52:22.681'
      }
    ]
  },
  {
    _id: '3d2343c2d4850aa2d9f0ae33',
    feedBucket: [
      {
        _id: '2a3535c2d4852ba2d9f0ae52',
        createdAt: '2018-02-30 21:52:22.681'
      },
      {
        _id: '9f342c2d4852ba2d9f0ae52',
        createdAt: '2018-06-30 21:52:22.681'
      }
    ]
  }
]

我正在尝试从用户feedBucket中提取ID为'9f342c2d4852ba2d9f0ae52'的文档。

await User.updateMany(
  {},
  { $pull: { feedBucket: { _id: '9f342c2d4852ba2d9f0ae52' } } },
  { multi: true }
)

但是它不起作用,结果是{n:2,nModified:0,ok:1}

1 个答案:

答案 0 :(得分:1)

如果您的feedBucket._id是ObjectId,则需要通过转换为猫鼬ObjectId来$pull

  const user = await User.update(
    { },
    { $pull: { feedBucket: { _id: mongoose.Types.ObjectId('5b07fa836569d356ba5bd2fa') } } },
    { multi: true }
  )