user12869402
user12869402

Reputation: 113

Remove items from Mongo Aggregation if contained in an item array

Using MongoDB Node.js

I have an products collection:

Example:

{
    _id: '12',
    linkedProducts: ['1234']
}

If I had a product ID with an ID of 1234, and it is linked to '12', what would be the best way to lookup through all products that has 1234 as a linked product?

Any help would be greatly appreciated.

Upvotes: 2

Views: 26

Answers (1)

eol
eol

Reputation: 24555

You can first use the $in operator on the array field to find documents where the array contains the given id and then use $pull to remove this value from the array:

db.collection.update({
  linkedProducts: {
    $in: [
      "1234"
    ]
  }
},
{
  $pull: {
    linkedProducts: "1234"
  }
},
{
  multi: true
})

Here's a working example on mongoplayground: https://mongoplayground.net/p/nlBUWLdKERS

Upvotes: 2

Related Questions