Matching an array field which contains any combination of the provided array in MongoDB

You can do this by combining multiple operators:

db.test.find({tags: {$not: {$elemMatch: {$nin: ['Rad', 'Cool']}}}})

The $elemMatch with the $nin is finding the docs where a single tags element is neither ‘Rad’ nor ‘Cool’, and then the parent $not inverts the match to return all the docs where that didn’t match any elements.

However, this will also return docs where tags is either missing or has no elements. To exclude those you need to add a qualifier that ensures tags has at least one element:

db.test.find({
    tags: {$not: {$elemMatch: {$nin: ['Rad', 'Cool']}}},
    'tags.0': {$exists: true}
})

Leave a Comment