In relational database, sometimes we need to construct sql string dynamically when the query is complex. For example , search an array of keywords, or query a range of values.

 
 
        $keywordssplit = explode(" " , trim($keywords));
 
        $filter = " and title like '"  ;
        foreach($keywordssplit as $keyword) {
            $filter .= '%' . $keyword ;
        }
        $filter .= '%\'';
        return $filter;
 

Or construct a range query

 
        foreach($category as $catitem) {
            $filter .= "'".$catitem."' ,";
        }
        $filter = substr($filter , 0, strlen($filter) - 1);
        $filter = " and category in (" . $filter . ")";
 
        return $filter;
 
 

How we do it in MongoDB?

In SQL, we can set a always true condition

 
 
$str = "select * from post where 1 = 1 and " . $criteria;
 
 

Even when the criteria is empty , the statement still works. For MongoDB, because the _id field is always present, we can set such a condition like this

 
$andarray = array();
$andarray[] = array('_id' => array ('$nin' => array( -1 ) ) ) ;
 
... add other conditions
 
$criteria = array('$and' => $andarray);
$count = $this->collection->find($criteria)->count();
 

The _id never be "-1", so the condition always true. To construct condition, for example an in range query:

 
        $in = array();
 
        foreach($catarray as $catitem) {
            $in [] = $catitem;
        }
 
 
        $cat_criteria = array('category' => array('$in' => $in ));
        return $cat_criteria;
 

An example of criteria :

 
Array
(
    [$and] => Array
        (
            [0] => Array
                (
                    [_id] => Array
                        (
                            [$nin] => Array
                                (
                                    [0] => -1
                                )
 
                        )
 
                )
 
            [1] => Array
                (
                    [category] => Array
                        (
                            [$in] => Array
                                (
                                    [0] => oracle
                                    [1] => concept
                                    [2] => plsql
                                )
 
                        )
 
                )
 
        )
 
)