mongo db findOne and $or does order of arguments matters or hierarchy? [performance]
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops
--
Chapters
00:00 Mongo Db Findone And $Or Does Order Of Arguments Matters Or Hierarchy? [Performance]
00:40 Accepted Answer Score 4
01:22 Answer 2 Score 4
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/2554...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #mongodb #performance #mongodbquery #pymongo
#avk47
ACCEPTED ANSWER
Score 4
Yes the order matters which is one strong reason for an array form of arguments which of course is ordered.
So basically this is referred to as "short circuit" evaluation. So only where the first condition does not match then is the next condition tested and so on.
So can best demonstrate with a collection like this:
{ "a": 1 },
{ "a": 2, "b": 1 }
And then the following query:
db.collection.find({ "$or": [ { "a": 1 }, { "b": 1 } ] })
Which of course finds both documents since even though the first does not have an element for "b" the first condition is met anyway. In the second document since the first failed then the second was used to match.
ANSWER 2
Score 4
I would like that it stops further searching when matchin first condition, so it not goes lower level to search around children.
The question you have to ask yourself is: How can MongoDB know how both sides of the $or are satisfied by one side? How does MongoDB know that the documents that do not satisfy the first condition do not satisfy the second?
If I were to say that I have a set of documents, half with {a:1,b:1} and half with {b:2} how can you know that a:1 OR b:1 is satisfied by the first half if you have no idea what the second half look like?
Simple answer is that it doesn't. It has to search both conditions (via parallel queries which are then returned and duplicates merged) as such order does not really matter unless it were an $and and in this case the importance of order is in the index not the query as the query will be moved around to optimise for quickest path to results.
So in reality the way MongoDB works is that it shoots off a "query" per condition. This actually explains the behaviour: http://docs.mongodb.org/manual/reference/operator/query/or/#behaviors
When using indexes with $or queries, each clause of an $or can use its own index.