Developer Blog

  • Blog
  • /
  • MongoDB driver almost here!
By Dracony on 5 November 2013

Today I finished the hardest part of making a MongoDB driver, support for nested logic like AND, OR XOR. By default MongoDB will not use indexes if the quesry has nested $or elements and will perform a full table scan. The only way to use indexes is to modify the query so that it is a single $or query with nested $and queries, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//This query:
{
    $and:[
        {$or:[A,B]},
        {$or:[C,D]}
    ]
}

//Has to be
{
    $or:
        [
            {$and:[A,C]},
            {$and:[A,D]},
            {$and:[B,C]},
            {$and:[B,D]}
        ]
}

Not only that, the worst part is that you can’t negate a subquery, making it even harder to implement things like XOR. Now I wanted a full query builder support in PHPixie (with any kind of negations and nested conditions), so that the developer would not have to think about inflating his queries to get all possible combinations. I’ve just finished writing a code that does just that. It will even try to optimize the end result, by removing duplicated queries and operands. The alorythm I used is efficient enough for making inflecting even of long and complex queries really really fast.

It took me a HUGE amount of time to come up with efficient ways of doing this, especially the negation part (hello De Morgan’s laws), but that part is done. So you all can expect a super useful MongoDB query builder when the ne DB module is released.

comments powered by Disqus