How does MongoDB evaluate multiple $ or operators?

How MongoDB will evaluate this query:

db.testCol.find(
{
    "$or" : [ {a:1, b:12}, {b:9, c:15}, {c:10, d:"foo"} ]
});

      

When scanning values ​​in a document, if the first OR operator is TRUE, will the other operators be evaluated as well?

Logically, if MongoDB is optimized, other values ​​in the OR statement shouldn't be evaluated, but I don't know how MongoDB is implemented.

UPDATE: I updated my query because it was wrong and it didn't explain correctly what I was trying to accomplish. I need to find a set of documents that have different properties, and if a combination of these properties is found accurate , the document should be returned.

The SQL equivalent of my query:

SELECT * FROM testCol 
WHERE (a = 1 AND b = 12) OR (b = 9 AND c = 15) OR (c = 10 AND d = 'foo'); 

      

+3


source to share


2 answers


MongoDB will execute each $ clause or operations as a separate query and remove duplicates as a post-processing pass. Thus, each sentence can use a separate index, which is often very useful.



In other words, it will NOT look at 1 document, see which of the OR clauses apply, and do it earlier if the first clause is a match. Rather, it makes a complete query of the dataset for the item and discards it after the fact. This may sound less efficient, but in practice it is almost always faster, as the first approach might hit at most one index for all entries, which are rarely effective.

+3


source


EDIT: Mongo only skips documents during the deduplication process, not during a table scan.

Mongo will not validate documents that are already part of the result set. So if your first {a: 1, b: 12} returns 100% of the documents, Mongo is done.

You want to put whatever will capture most of the documents as your first graded statement because of this. If your first item only captures 1% of the documents, the subsequent item will have to scan the other 99%.



When doing this, you use $ or to look up values ​​in one key. I think you want to use $ in for this.

See here for more details:

http://books.google.com/books?id=BQS33CxGid4C&lpg=PA48&ots=PqvQJPRUoe&dq=mongo%20tips%20and%20tricks%20%22OR-query%22&pg=PA48#v=onepage&q&f=false

+1


source







All Articles