Search code examples
mongodbmongo-java

Expressions sequence in OR query of MongoDB


reading the documentations of OR queries of MongoDB the syntax of OR is :

Syntax: { $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] } 

The thing I didn't understand is the sequence in which theses expression executes. i.e

get documents matching expression-1 if nothing is found get documents matching expression-2 ect ... Is it true that expression execute one after other or ?

and what does it mean: " When using indexes with $or queries, remember that each clause of an $or query will execute in parallel."


Solution

  • There is no particular order to a queries execution whether it be:

    db.col.find({ name: 's', c: 1 });
    

    Or:

    db.col.find({$or: [{name: 's'}, {c: 1}]})
    

    In an $or MongoDB will effectively make x queries based on the number of conditions you have in your $or, return a result for each clause, merge duplicates and then return the result (simply put). Due to this behaviour MongoDB can actually use multiple indexes for an $or clause, and at the minute only an $or clause.

    This is important to note when making compound indexes. Indexes do require a certain structure to the query sometimes to work at optimal pace. As such if you have a compound index of:

    {name: 1, c: 1}
    

    It may not match both clauses of:

     db.col.find({$or: [{name: 's'}, {c: 1}]})
    

    In a performant manner. So this is something you must bare in mind here with the parallelism of $or clauses. If you wish to check that all clauses use indexes you can use an explain() on the end which will break down the clauses and their usage for you.