PHP 從 MongoDb 中查詢數據怎么樣實現


一、軟件環境(版本非必須) php v5.6 擴展:MongoDB nginx v1.11 mongodb v3.2

note: 必須安裝MongoDB擴展

二、連接 $client = new MongoClient($server, $option);

$server 變量是個字符串,描述要連接的服務器

mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db

其中必要的是:

username 數據庫用戶名 password 數據庫密碼 host 服務器地址 port 數據庫監聽端口 三、選表(集合) 選擇數據庫 選擇集合 $db = $client->{$db_name};

返回MongoDB類 類文檔傳送門

$collection = $db->{$collection_name};

返回MongoCollection類 類文檔傳送門

四、查詢數據 $cursor = $collection->find($filter);

返回MongoCursor類 類文檔傳送門

1. $filter參數

mongoshell find函數參數使用:傳送門

php代碼編寫

// 查詢值大於value的文檔 $filter[$gtKey] = array('$gt' => $value); // regexKey模糊查詢 $filter[$regexKey] = new MongoRegex('/'.$regexValue.'/'); $collection->find($filter);

注意:

模糊查詢需要使用MongoRegex類來使用,否則不識別 比較大小時,$value 的值需要與mongodb中存儲的類型一致 2. 利用MongoCursor進行分頁等操作 // 返回MongoCursor,可以利用MongoCursor的方法遍歷數據 // 或者使用iterator_to_array($cursor)轉換成數組 $cursor = $cursor ->sort(array($field=>'-1 or 1')) // 1是正序,-1是反序 ->skip($start) // 數據起始位置 ->limit($size); // 數據結束位置為$start+$size // 返回int型數值 $count = $cursor ->find($filter) ->count(); $data = iterator_to_array($cursor)

不再講解如何使用MongoCursor遍歷數據

五、總結

使用php連接MongoDB查詢數據總體來說非常簡單。連接、根據條件查詢、分頁,三步搞定。

注意事項:

使用單例模式獲取MongoDB實例 模糊查詢需要借助MongoRegex類 操作完成要** 關閉連接 **

That’s right. This article was first published in March 2016, buttimes change, new themes are launched for sale, so we’ve stripped out themes which are no longer available andadded eight new examples to keep things up to date.

1. Introduce Yourself

Emotional design is hugely important on the web; add the “human element” to your portfolio and your visitors will more likely connect with the work you show them. Make sure they know who they’re dealing with, who’s responsible for the photos, and who it is they’ll need to get in touch with if they want to know more.

The Responsive Photography Theme by ThemeGoods offers a homepage layout which does this really well. Your name, your signature, a touch of personality up front and centre.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM