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.
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