Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB $pull from array with filter

I have User collection:

[
  {
    _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'
      }
    ]
  }
]

And I am trying to pull document with id - '9f342c2d4852ba2d9f0ae52' from users feedBucket.

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

but it doesn't work, result is { n: 2, nModified: 0, ok: 1 }

like image 868
koasi Avatar asked Jan 18 '26 09:01

koasi


1 Answers

If your feedBucket._id is ObjectId then you need to $pull it by converting to mongoose ObjectId

  const user = await User.update(
    { },
    { $pull: { feedBucket: { _id: mongoose.Types.ObjectId('5b07fa836569d356ba5bd2fa') } } },
    { multi: true }
  )
like image 139
Ashh Avatar answered Jan 20 '26 00:01

Ashh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!