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

I would like to query with a specified list of array elements so that the returned documents can only contain the elements that I am passing in, but should not contain all of them.

These documents are like:

{
  name: "Article 1",
  tags: ["Funny", "Rad"]
}

{
  name: "Article 2",
  tags: ["Cool", "Rad]
}

{
  name: "Article 3",
  tags: ["Rad"]
}

      

Here are some examples of arrays and their corresponding results.

  • ["Rad"]

    should return article 3
  • ["Rad", "Cool"]

    must return articles 2 and article 3
  • ["Funny", "Cool"]

    shouldn't return anything as there are no articles with one of these tags or both

I'm sure I can do it with help $where

, but I would like to avoid it for obvious reasons.

+3


source to share


1 answer


You can do this by concatenating several operators:

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

      

$elemMatch

c $nin

finds documents in which one element tags

is neither "Rad" nor "Cool", and then the parent $not

inverts the match to return all documents that do not match any elements.



However, this will also return documents that are tags

either missing or have no elements. To exclude the ones you need to add a qualifier that ensures it tags

has at least one element:

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

      

+5


source







All Articles