Find documents with array that doesn't contains a specific value Find documents with array that doesn't contains a specific value mongoose mongoose

Find documents with array that doesn't contains a specific value


Nothing wrong with what you are basically attempting, but perhaps the only clarification here is the common misconception that you need operators like $nin or $in when querying an array.

Also you really need to do here is a basic inequality match with $ne:

Person.find({ "groups": { "$ne": group._id } })

The "array" operators are not for "array targets" but for providing a "list" of conditions to test in a convenient form.

Person.find({ "groups": { "$nin": [oneId, twoId,threeId] } })

So just use normal operators for single conditions, and save $in and $nin for where you want to test more than one condition against either a single value or a list. So it's just the other way around.

If you do need to pass a "list" of arguments where "none" of those in the provided list match the contents of the array then you reverse the logic with the $not operator and the $all operator:

Person.find({ "groups": { "$not": { "$all": [oneId,twoId,threeId] } } })

So that means that "none of the list" provided are present in the array.


This is a better way to do this in Mongoose v5.11:

Person.find({ occupation: /host/ }).where('groups').nin(['group1', 'group2']);

The code becomes clearer and has more readability.