I have an Array of objectId's and would like to get all documents except these ids in an array element in object

I want to remove all elements in results that doesn’t match the id in the array [ObjectId(“605a3a82c8bbb404f4e6b123”),ObjectId(“605a3a82c8bbb404f4e6b125”)]

{
_id: 1,
results: [
{_id: ObjectId(“605a3a82c8bbb404f4e6b643”), item: “A”, score: 5, },
{_id: ObjectId(“605a3a82c8bbb404f4e6b123”), item: “B”, score: 8 }
]
}
{
_id: 2,
results: [
{_id: ObjectId(“605a3a82c8bbb404f4e6b643”), item: “A”, score: 5, },
{_id: ObjectId(“605a3a82c8bbb404f4e6b123”), item: “B”, score: 8 },
{_id: ObjectId(“605a3a82c8bbb404f4e6b124”), item: “D”, score: 2, },
{_id: ObjectId(“605a3a82c8bbb404f4e6b125”), item: “C”, score: 1 }
]
}

I tried addFields with no luck, i am a bit confused

{
$addFields: {
results: {
$filter: {
“input”: “$results”,
“as”: “r”,
“cond”: {
$in: [
“$r._id”,
$removalList
]
}
}
}
}
}

This will be true for all elements that you want to remove. If you look at $filter’s documentation, you will see that cond:true is used to specify elements you want to keep.

If removalList is not a field in your document, you should simply used removalList rather than $removalList.

1 Like