## PHP安裝MongoDB擴展驅動
window上安裝 MongoDB PHP擴展:
<!--more-->
Github上已經提供了用于window平臺的預編譯php mongodb驅動二進制包([下載地址](https://s3.amazonaws.com/drivers.mongodb.org/php/index.html)),你可以下載與你php對應的版本,但是你需要注意以下幾點問題:
1.安裝的版本要與安裝的PHP版本一致,例如php_mongo-1.6.8-5.4-vc9.dll運行環境是PHP5.4_ts_x86版本,且系統環境至少為vc9。
2.'Thread safe'(線程安全)是運行在Apache上以模塊的PHP上,如果你以CGI的模式運行PHP,請選擇非線程安全模式(' non-thread safe')。
3.下載完你需要的二進制包后,解壓壓縮包,將'php_mongo.dll'文件添加到你的PHP擴展目錄中(ext)。ext目錄通常在PHP安裝目錄下的ext目錄。
打開php配置文件 php.ini 添加以下配置:
```
extension=php_mongo.dll
```
重啟服務器。
通過瀏覽器訪問phpinfo,如果安裝成功,就會看到mongo。
## PHP操作mongodb
PHP已經提供了一系列的Mongo操作類:
http://php.net/manual/zh/book.mongo.php
`MongoClient類`
這個類用于創建和管理連接。
`MongoClient`
基本用法
```
<?php
$m = new MongoClient(); // 連接
$db = $m->foo; // 獲取名稱為 "foo" 的數據庫
?>
```
```
Table of Contents
MongoClient::close — 關閉連接
MongoClient::connect — 連接到數據庫服務器
MongoClient::__construct — 創建一個新的數據庫連接對象
MongoClient::dropDB — 刪除一個數據庫 [已廢棄]
MongoClient::__get — 取得一個數據庫
MongoClient::getConnections — 返回所有已打開連接的信息
MongoClient::getHosts — 更新所有關聯主機的狀態信息
MongoClient::getReadPreference — 獲取此連接的讀取首選項
MongoClient::getWriteConcern — Get the write concern for this connection
MongoClient::killCursor — Kills a specific cursor on the server
MongoClient::listDBs — 列出所有有效數據庫
MongoClient::selectCollection — 獲取數據庫的文檔集
MongoClient::selectDB — 獲取一個數據庫
MongoClient::setReadPreference — 為該連接設置讀取選項
MongoClient::setWriteConcern — Set the write concern for this connection
MongoClient::__toString — 該連接的字符串表達方式
```
`MongoDB類`
該類的實例用于和數據庫進行交互。例如:要獲取一個數據庫:
```
<?php
$m = new MongoClient(); // 連接
$db = $m->selectDB("test");
?>
```
```
Table of Contents
MongoDB::authenticate — 登錄到數據庫
MongoDB::command — 執行一條 Mongo 指令
MongoDB::__construct — 選擇一個數據庫
MongoDB::createCollection — 創建一個集合
MongoDB::createDBRef — 創建數據庫引用
MongoDB::drop — 丟棄數據庫
MongoDB::dropCollection — Drops a collection [deprecated]
MongoDB::execute — 在數據庫服務器上運行JavaScript
...
```
`MongoCollection類`
提供對集合的操作,如增刪查改。
```
Table of Contents
MongoCollection::aggregate — Perform an aggregation using the aggregation framework
MongoCollection::aggregateCursor — Execute an aggregation pipeline command and retrieve results through a cursor
MongoCollection::batchInsert — Inserts multiple documents into this collection
MongoCollection::__construct — 創建一個新的集合
MongoCollection::count — 返回集合中的文檔數量
MongoCollection::createDBRef — 創建一個數據庫引用
MongoCollection::createIndex — Creates an index on the specified field(s) if it does not already exist.
MongoCollection::deleteIndex — Deletes an index from this collection
MongoCollection::deleteIndexes — 刪除集合的所有索引
MongoCollection::distinct — 獲取集合里指定鍵的不同值的列表。
MongoCollection::drop — 刪除該集合
MongoCollection::ensureIndex — Creates an index on the specified field(s) if it does not already exist.
MongoCollection::find — 查詢該集合,并返回結果集的 MongoCursor
MongoCollection::findAndModify — Update a document and return it
MongoCollection::findOne — Queries this collection, returning a single element
MongoCollection::__get — Gets a collection
MongoCollection::getDBRef — Fetches the document pointed to by a database reference
MongoCollection::getIndexInfo — Returns information about indexes on this collection
MongoCollection::getName — 返回這個集合的名稱
MongoCollection::getReadPreference — Get the read preference for this collection
MongoCollection::getSlaveOkay — Get slaveOkay setting for this collection
MongoCollection::getWriteConcern — Get the write concern for this collection
MongoCollection::group — Performs an operation similar to SQL GROUP BY command
MongoCollection::insert — 插入文檔到集合中
MongoCollection::parallelCollectionScan — Returns an array of cursors to iterator over a full collection in parallel
MongoCollection::remove — 從集合中刪除記錄
MongoCollection::save — 保存一個文檔到集合
MongoCollection::setReadPreference — Set the read preference for this collection
MongoCollection::setSlaveOkay — Change slaveOkay setting for this collection
MongoCollection::setWriteConcern — Set the write concern for this database
MongoCollection::toIndexString — Converts keys specifying an index to its identifying string
MongoCollection::__toString — String representation of this collection
MongoCollection::update — Update records based on a given criteria
MongoCollection::validate — Validates this collection
```
`MongoCursor類`
用來遍歷結果。例如:
```
<?php
$cursor = $collection->find();
var_dump(iterator_to_array($cursor));
?>
```
## 實戰
```
<?php
$m = new MongoClient();
$db = $m->test; //選擇test數據庫
$c = $db->user; //選擇一個集合
//find
function get($c){
$list = $c->find();
if(is_object($list))
foreach($list as $k=>$vo){
$data = array(
//'id' => $vo['_id'],
'name' => $vo['name'],
'age' => $vo['age'],
'birthday' => $vo['birthday']
);
if(empty($vo['age'])) unset($data['age']);
if(empty($vo['birthday'])) unset($data['birthday']);
$res[] = $data;
}
return $res;
}
function gets($c){
$list = $c->find();
var_dump(iterator_to_array($list));
}
$list = get($c);
//var_dump($list);
//update
$where = array('name'=>'yjc');
$new_arr = array(
'name' => 'yjc',
'age' => 25,
'birthday' => '1992-02-18'
);
//echo $res = $c->update($where, $new_arr); //全量更新,必須跟全部字段
//局部更新
$where = array('birthday'=>'1992-02-18');
$new_arr = array('$set' =>array('name' => 'yujc', 'age' => 25)); //注意用法,全部寫在$set修改器數組里
//$res = $c->update($where, $new_arr);
//新增
$arr = array(
'name' => 'jiancai2',
'age' => 21,
'birthday' => '1993-02-18'
);
//$res = $c->insert($arr); var_dump($res);
//刪除
$where = array('name'=>'jiancai2');
$res = $c->remove($where); var_dump($res);
//count
$user_num = $c->count();
var_dump($user_num);
//var_dump(get($c));
gets($c);
```