2012-06-28 61 views
2

我正在尋找一個MongoDB查找查詢,只發現任何與字符串中的圖像,它的搜索是一個文件類型標題,所以它通常看起來像圖像/ PNG或文本/ HTML 。正則表達式MongoDB PHP查詢

我運行此代碼爲正則表達式:

array('fileType'=>array('$regex'=>'^image')) 

而這種代碼總數:

foreach ($this->grid->find(array('fileType'=>array('$regex'=>'^image'))) as $file) { 
         $id = (string) $file->file['_id']; 
         $filename = htmlspecialchars($file->file["filename"]); 
         $filetype = isset($file->file["filetype"]) ? $file->file["filetype"] : 'application/octet-stream'; 

         if($filetype == 'image/'.$chosenfile.''){ 
          $links[] = sprintf('<img src="lib/download.php?id=%s" height="200px" width="200px">', $id); 
         }elseif($chosenfile == ''){ 
          $links[] = sprintf('<img src="lib/download.php?id=%s" height="200px" width="200px">', $id); 
         } 
        } 
+0

是它返回一個錯誤? – Aaron

回答

9

這是你的問題:

array('$regex'=>'^image') 

應該使用MongoRegex object:

array('fileType' => new MongoRegex('/^image/i')) 

此處的文檔定義如下:http://www.php.net/manual/en/class.mongoregex.php

它現在可以工作嗎?

+0

現在不推薦使用class.mongoregex.php。那麼我現在該如何使用這個課程呢?請參考:http://php.net/manual/en/class.mongoregex.php –

+3

@MansoorH'(new \ MongoDB \ Client) - > db-> collection-> find(['d'=> new \ MongoDB \ BSON \ Regex('^ image','i')])'就像這樣 – Sammaye

0

檢查以下MongoDB實例查詢使用PHP它的作品..

$pipeline = array(
       array('$match' => array(
            '$and' => array(array('data_UTC' => array('$gte' => new MongoDate(strtotime('2017-01-20T00:00:00-02:00')), 
                       '$lt' => new MongoDate(strtotime('2017-01-29T00:00:00-02:00')) 
                     ), 
                  'carga' => array('regex' => new MongoRegex('/^soja/i')) 
                 ) 
               ) 
           ) 
       ), 
       array('$group' => array('_id' => array('$dataToString' => array('format' => '%Y-%m-%d', 'date' => array('$subtract' => array('$data_UTC', 1000 * 60 * 60 * 2)))), 'qtd_acessos' => array('$sum' => 1))), 
       array('$sort' => array('_id' => -1)), 
       array('$limit' => 50) 
      ); 
$results = $this->mongodb->aggregate($pipeline);