1

I have started work with lithium framework + mongoDB recently. I want to do a really simple query which contains multiple or statements. I have articles in the DB with publish_up and publish_down fields. I want to fetch only those records/documents which pulbis_down field is highert than now OR null AND publish_up field lower than now OR null.

$items = $article::find('all', array(
    'conditions' => array(
        '$or' => array(
            '$gt' => array('publish_down', $mongoDateNow),
            'publish_down' => $mongDateNull
        ),
        '$or' => array(
            '$lt' => array('publish_up', $mongoDateNow),
            'publish_up' => $mongDateNull
        ),
    )
));

Of course this snippet is wrong hence the second or statement overwrites the first one (because the same array key). I tried to wrap them into an individual array but gives error. Any idea?

3 Answers3

3

This query will fetch articles with (publish_down > now OR publish_down = null) AND (publish_up < now OR publish_up = null)

    $items = Articles::find('all', array(
        'conditions' => array(
            '$or' => array(
                array('publish_down' => array('$gt' => $mongoDateNow)),
                array('publish_down' => null)
            ),
            '$or' => array(
                array('publish_up' => array('$lt' => $mongoDateNow)),
                array('publish_up' => null)
            ),
        )
    ));
Mehdi Lahmam B.
  • 2,240
  • 16
  • 22
0

I don't know about lithium but in PHP you can use multiple $OR as below

$items = $article::find('all', array(
    'conditions' => array(
        '$or' => array(
        array(
            '$gt' => array('publish_down', $mongoDateNow),
            'publish_down' => $mongDateNull
        ),
        array(
            '$lt' => array('publish_up', $mongoDateNow),
            'publish_up' => $mongDateNull
        )
        ),
    )
));
GBD
  • 15,847
  • 2
  • 46
  • 50
0

I think the correct answer is:

'$and' => array(
    array(
        '$or'=>array(
            array('publish_up' => null),
            array('publish_up' => array('$lt' => $mongoDateNow))
        )
    ),
    array(
        '$or'=>array(
            array('publish_down' => null), 
            array('publish_down' => array('$gt' => $mongoDateNow))
        )
    )
)
Minh Nguyen
  • 490
  • 1
  • 3
  • 8