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

前端 未结 1 1045
渐次进展
渐次进展 2020-11-28 14:17

I would like to query with a specified list of array elements such that documents returned can only contain the elements I pass, but need not contain all of them.

Gi

相关标签:
1条回答
  • 2020-11-28 14:39

    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}
    })
    
    0 讨论(0)
提交回复
热议问题