0

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 }
    }
}

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.