Query documents, but only return those whose ID is not found in arbitrary array of ID's

So I have an aggregation and I just can’t figure out how to match against an array of ID’s. I’ve tried several methods and approaches but all have failed, been at this for a while now so any assistance would be very much appreciated. Some pseudo code of what I’m looking for:

const IdArr = [randId1, randId2, ....]

UserModel.aggregate([ $match: $cond: !IdArr.includes(_id) ]).sample(n)

obviously that doesn’t work and the actual solution will look radically different, but I hope that helps convey exactly what I’m trying to do. Create an aggregate of a certain document type, exclude any docs whose ID is included in IdArr, then randomly sample the remaining docs.

Thanks in advance for any help!!!

See https://www.mongodb.com/docs/manual/reference/operator/query/nin/

and https://www.mongodb.com/docs/manual/reference/operator/aggregation/sample/

Ah excellent $nin is exactly what I’m searching for. How would that be used here? Just

UserModel.aggregate([ $match: { id: { $nin: <my_arr>}}])

?

1 Like

Often, you will get a faster turn around by just trying.

It should work like that, one you fix your syntax error caused by the missing opening brace for your $match stage.

1 Like