Antoine Bellion
Antoine Bellion

Reputation: 136

Querying for array whose values are in the specified array

Taking this document :

{
    "targets": [
        ['a', 'b'],
        ['a']
    ]
}

I would like to retrieve it with the following targets :

['a', 'b']
['a']
['a', 'b', 'c'] //because one target contains 'a' and 'b'

And not with this one :

['b'] //because non of the targets contains only 'b'

I tried with this query criteria but it doesn't work at all :

'targets': {
    '$elemMatch': {
        '$elemMatch': { '$in': target }
    }
}

Upvotes: 0

Views: 35

Answers (1)

s7vr
s7vr

Reputation: 75984

You can use below find query.

db.collection.find({
    targets: {
      $elemMatch: {
        $not: {
            $elemMatch: {
                $nin: input array
            }
        }
    }
  }
});

$elemMatch with $nin selects all the documents with targets element have at least one array element with no value matching element in input array.

db.collection.find({
    targets: {
      $elemMatch: {
            $elemMatch: {
                $nin: input array
        }
    }
  }
});

input array - selection

['a', 'b'] - false
['a'] - false
['a', 'b', 'c'] - false
['b'] - true

$not to select the documents where targets element have array element which is subset of input array.

db.collection.find({
    targets: {
      $elemMatch: {
        $not: {
            $elemMatch: {
                $nin: input array
            }
        }
    }
  }
});

input array - selection

['a', 'b'] - true
['a'] - true
['a', 'b', 'c'] - true
['b'] - false

Upvotes: 1

Related Questions