首先安裝擴展,然後才能使用mongodb 一、連接資料庫 try { $mongo = new MongoClient(); $db = $mongo->mydb; var_dump($db); } catch (MongoConnectionException $e) { echo $e->get
首先安裝擴展,然後才能使用mongodb
一、連接資料庫
try { $mongo = new MongoClient(); $db = $mongo->mydb; var_dump($db); } catch (MongoConnectionException $e) { echo $e->getMessage(); }
該代碼可以連接mydb資料庫,如果該資料庫不存在則自動創建。
二、創建集合
try { $mongo = new MongoClient(); $db = $mongo->mydb; $mycol = $db->createCollection('mycol'); var_dump($mycol); } catch (MongoConnectionException $e) { echo $e->getMessage(); }
該代碼可以創建集合mycol。
三、插入文檔
mongodb中使用insert()來插入文檔。
try { $mongo = new MongoClient(); $db = $mongo->mydb; $mycol = $db->mycol; $document = array('name' => 'test1' , 'sex' => 'formale' , 'age' => 20); $res = $mycol->insert($document); var_dump($res); } catch (MongoConnectionException $e) { echo $e->getMessage(); }
輸出:
array (size=4) 'ok' => float 1 'n' => int 0 'err' => null 'errmsg' => null
四、查找文檔
mongodb使用find()來查找文檔
try { $mongo = new MongoClient(); $db = $mongo->mydb; $mycol = $db->mycol; $mongoCursor = $mycol->find(); foreach ($mongoCursor as $document) { var_dump($document); } } catch (MongoConnectionException $e) { echo $e->getMessage(); }
結果:
array (size=4) '_id' => object(MongoId)[7] public '$id' => string '56c28a793b22cf5415000029' (length=24) 'name' => string 'test1' (length=5) 'sex' => string 'formale' (length=7) 'age' => int 20
五、更新文檔
使用update()來更新文檔
try { $mongo = new MongoClient(); $db = $mongo->mydb; $mycol = $db->mycol; $mycol->update(array('name'=>'test1') , array('$set'=>array('age' => 21))); $mongoCursor = $mycol->find(); foreach ($mongoCursor as $document) { var_dump($document); } } catch (MongoConnectionException $e) { echo $e->getMessage(); }
結果
array (size=4) '_id' => object(MongoId)[7] public '$id' => string '56c28a793b22cf5415000029' (length=24) 'name' => string 'test1' (length=5) 'sex' => string 'formale' (length=7) 'age' => int 21
六、刪除文檔
try { $mongo = new MongoClient(); $db = $mongo->mydb; $mycol = $db->mycol; $mycol->remove(array('name'=>'test1')); $mongoCursor = $mycol->find(); foreach ($mongoCursor as $document) { var_dump($document); } } catch (MongoConnectionException $e) { echo $e->getMessage(); }
remove方法
public bool|array MongoCollection::remove ([ array $criteria = array() [, array $options = array() ]] )
options刪除的選項:
“w”:拋出異常的級別,預設是1;
“justOne”:最多只刪除一個匹配的記錄;
“fsync”:Boolean, defaults to FALSE
. Forces the insert to be synced to disk before returning success. If TRUE
, an acknowledged insert is implied and will override setting w to 0.
“timeout”:Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, aMongoCursorTimeoutException will be thrown.
......
其他方法可參見php手冊:http://php.net/manual/zh/book.mongo.php