Mongo db findOne and $ or argument order or hierarchy? [representation]

I mean, for example, if you have two conditions: if the first condition is true, then it avoids checking the second?

doc = collection.find_one(
    {'$or': [
              {
               'k': kind,
               'i': int(pk)
              },
              {
               'children.k': kind, 
               'children.i': int(pk)
              }

            ]
    }, { '_id': False})

      

I would like it to stop further searching when the first condition is matched, so it doesn't go to a lower level for searching around children.

Is it a matter of the order of the arguments in the $OR

closure, or rather does mongodb know the hierarchy skillfully and affect the order of the search findOne

?

+3


source to share


2 answers


Yes, order matters, which is one of the strong reasons for an array of arguments, which are of course ordered.

So basically this is called the "short circuit" rating. That way, only when the first condition doesn't match is the next condition checked, etc.

So it's best to demonstrate with a collection like this:

{ "a": 1 },
{ "a": 2, "b": 1 }

      



And then the following request:

db.collection.find({ "$or": [ { "a": 1 }, { "b": 1 } ] })

      

Which of course finds both documents, since even if the first does not have an element for "b", the first condition is satisfied anyway. In the second document, since the first failed, the second was used for matching.

+2


source


I would like it to stop further searching on the first matchin condition, so it doesn't go down to a lower level for searching around children.

The question you will ask yourself is this: How does MongoDB know how both sides are $or

satisfied with one side? How does MongoDB know that documents that do not satisfy the first condition do not satisfy the second?

If I said I have a set of documents, half s {a:1,b:1}

and half s {b:2}

, how can you know what a:1 OR b:1

the first half is doing if you don't know what the second half looks like?



The simple answer is no. It has to look for both conditions (via parallel queries that are then returned and the duplicates are merged) since that order doesn't matter if it wasn't $and

, in which case the importance of the order is specified in the index, not how the query as query will move to optimize the fast path to results.

So the way MongoDB really works is that it shoots a "query" for each condition. This actually explains the behavior: http://docs.mongodb.org/manual/reference/operator/query/or/#behaviors

When using indexes with $ or queries, each $ or item can use its own index.

+2


source







All Articles