MongoDB search using a date range and another condition
mongodb, php
Solution
A1/A2: You don't need the $and like that, instead use:
$searchCriteria = array(
'date' => array('$gt' => $start, '$lte' => $end),
'lid' => $lid
);
On the shell, this `{"$and":{"date":{"$gt":"2010-11-10","$lte":"2010-11-12"},"lid":6209}}` is incorrect, as you need to use an array (with []) and not an object (which is {}). Correct is:
{"$and":[ {"date":{"$gt":"2010-11-10","$lte":"2010-11-12"} }, {"lid":6209} ]}
But you don't need the `$and` and you can just use:
db.largedaily.find( {"date":{ "$gt":"2010-11-10","$lte":"2010-11-12"}, {"lid":6209 } );
Problem
I'm trying to query the mongodb for documents having a 'date' attribute that is in a certain date range, this is how I'm doing it. Q1. ``` $searchCriteria = array('$and' => array( 'date' => array('$gt' => $start, '$lte' => $end), 'lid' => $lid )); ``` Q2. ``` $results = $collection->find($searchCriteria); ``` It doesn't return anything, but if I run each search criteria separately, they work. Q3. ``` $searchCriteria = array( 'date' => array('$gt' => $start, '$lte' => $end) ); ``` This works, it returns the documents that match this date range ``` $searchCriteria = array( 'lid' => $lid ); ``` This works too, returns all lid's equal to what I have requested. But when I want to AND these to conditions, it doesn't work, here is the var_dump of the search criteria Q1: ``` array(1) { '$and' => array(2) { 'date' => array(2) { '$gt' => string(10) "2010-11-10" '$lte' => string(10) "2010-11-12" } 'lid' => int(6209) } } ``` Here is the json_encoded output of the same query: ``` {"$and":{"date":{"$gt":"2010-11-10","$lte":"2010-11-12"},"lid":6209}} ``` Running the json output of the query in mongo shell results in an error ``` db.largedaily.find({"$and":{"date":{"$gt":"2010-01-01","$lte":"2010-01-02"},"lid":6209}}); error: { "$err" : "$and expression must be a nonempty array", "code" : 14816 } ``` What am I doing wrong? I think I'm setting the searchCriteria incorrectly.