1

We have a data structure in which we have an array (in actuality the array is of subdocuments):

{ "someField" : ["value1", "value2"]}

We have constructing a query like this:

db.collection.find({"someField":{ 
                       $in :["value1", "blah"], 
                       $not : { $in : ["value2"]}}})

NOTE: I know we don't need the second in for a single value but we need to support multiples.

When have an index on someField. If you just query on in and do an explain, the indexBounds looks like:

  "indexBounds": {"someField:[["value1","value1"], ["blah", "blah"]]}

This works great with efficient use of the index. When you run the query if the in and the not in we had hoped it would use the same bounds and then test the scanned objects for the not condition. Instead the indexBounds looks like this:

  "indexBounds": {"someField:[[{"$minElement":1}, "value2"], [value2 : {"$maxElement":1}]]}

This results is scanning the entire collection.

Are we doing something wrong? Is there some other way to constructor this query.

Currently the only solution we can up with was to do an aggregate with multiple match statements (one with the inclusive portion first, then the exclusive portion). Funny thing about that is that if you do {match, match} in an aggregate, they are combined and you end up with the same result so we had to do {match, project, match} to make each match distinct so that the first would use the index as desired.

NOTE: I cannot copy / paste from my work system so I cannot copy the entire explain.

1 Answer 1

1

I think you have a proper index and are constructing the query in the natural and correct way. You can use $nin instead of $not with $in, but it doesn't change index selection. This is an instance where SERVER-12281 would be helpful, but that feature hasn't been implemented yet.

1
  • Thanks for pointing out $nin and 12281. It looks like 12281 is exactly the reason. Bummer. Is the suggested aggregate an appropriate way to get around this?
    – John B
    Nov 10, 2014 at 18:59

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.