天天看點

[MongoDB] 使用PHP在MongoDB中搜尋的實作

條件操作符用于比較兩個表達式并從mongoDB集合中擷取資料。

MongoDB中條件操作符有:

(>) 大于 - $gt

(<) 小于 - $lt

(>=) 大于等于 - $gte

(<= ) 小于等于 - $lte

MongoDB 使用 $regex 操作符來設定比對字元串的正規表達式,使用PCRE (Perl Compatible Regular Expression) 作為正規表達式語言。

MongoDB OR 條件語句使用了關鍵字 $or

下面是具體一個PHP例子中的$filter數組:

array(3) {
  ["$or"]=>
  array(2) {
    [0]=>
    array(1) {
      ["modelID"]=>
      string(12) "基礎新聞"
    }
    [1]=>
    array(1) {
      ["name"]=>
      string(12) "基礎新聞"
    }
  }
  ["createTime"]=>
  array(2) {
    ["$gte"]=>
    string(19) "2020-02-18 00:00:00"
    ["$lte"]=>
    string(19) "2020-02-18 23:59:59"
  }
  ["modelXML"]=>
  array(1) {
    ["$regex"]=>
    string(6) "标題"
  }
}           

複制

$filter=$this->parseSearchQuery($q);
        //分頁顯示
        $options = [
            'skip'=>($page - 1) * $pageSize,
            'limit'=>$pageSize,
            'sort' => ['createTime' => -1],
            'projection'=>['_id'=> False, "modelXML"=> False],
        ];
        var_dump($filter);
        $mongoManger = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
        $query = new MongoDB\Driver\Query($filter, $options);
        $cursor = $mongoManger->executeQuery('.article', $query);
        if($cursor->isDead()){
            return [];
        }
        $list=[];
        foreach ($cursor as $document) {
            $list[]=$document;
        }
        return $list;           

複制