標籤:
最近有個項目,需要用php操作mongoDb資料,整理如下 1,串連MongoDB資料庫
| $conn = new Mongo();其他連結方式//$conn=new Mongo(); #串連本地主機,預設連接埠.//$conn=new Mongo(“172.21.15.69″); #串連遠程主機//$conn=new Mongo(“xiaocai.loc:10086″); #串連指定連接埠遠程主機//$conn=new Mongo(“xiaocai.loc”,array(“replicaSet”=>true)); #負載平衡//$conn=new Mongo(“xiaocai.loc”,array(“persist”=>”t”)); #持久串連//$conn=new Mongo(“mongodb://sa:[email protected]”); #帶使用者名稱密碼//$conn=new Mongo(“mongodb://localhost:27017,localhost:27018″); #串連多個伺服器//$conn=new Mongo(“mongodb:///tmp/mongo-27017.sock”); #域通訊端//$conn=new Mongo(“mongodb://admin_miss:[email protected]:27017/test”,array(‘persist’=>’p‘,”replicaSet”=>true)); #完整 |
2,選擇資料庫與表 $db=$conn->mydb; #選擇mydb資料庫 $collection=$db->myTable; #選擇集合(選擇’表’) //$collection=$db->selectCollection(myTable); #第二種寫法 //$collection=$conn->mydb->myTable; #更簡潔的寫法 3,插入資料記錄
| $array=array(‘column_name’=>’col’.rand(100,999),’column_exp’=>’xiaocai’);$result=$collection->insert($array); #簡單插入echo “新記錄ID:”.$array[‘_id‘]; #MongoDB會返回一個記錄標識var_dump($result); #返回:bool(true)//**向集合中安全插入資料,返回插入狀態(數組). **/$array=array(‘column_name’=>’col’.rand(100,999),’column_exp’=>’xiaocai2′);$result=$collection->insert($array,true); #用於等待MongoDB完成操作,以便確定是否成功.(當有大量記錄插入時使用該參數會比較有用)echo “新記錄ID:”.$array[‘_id‘]; #MongoDB會返回一個記錄標識var_dump($result); #返回:array(3) { ["err"]=> NULL ["n"]=> int(0) ["ok"]=> float(1) } |
4,更新資料記錄
| //** 修改更新 傳統更新 **/$where=array(‘column_name’=>’col123′);$newdata=array(‘column_exp’=>’GGGGGGG’,‘column_fid’=>444);$result=$collection->update($where,array(‘$set’=>$newdata)); #$set:讓某節點等於給定值,類似的還有$pull $pullAll $pop $inc,在後面慢慢說明用法/** 結果:* 原資料* {“_id”:ObjectId(“4d635ba2d549a02801000003″),”column_name”:”col123″,”column_exp”:”xiaocai”}* 被替換成了* {“_id”:ObjectId(“4d635ba2d549a02801000003″),”column_name”:”col123″,”column_exp”:”GGGGGGG”,”column_fid”:444}*///** 替換更新 ,覆蓋原記錄**/$where=array(‘column_name’=>’col709′);$newdata=array(‘column_exp’=>’HHHHHHHHH’,‘column_fid’=>123);$result=$collection->update($where,$newdata);/** 結果:* 原資料* {“_id”:ObjectId(“4d635ba2d549a02801000003″),”column_name”:”col709″,”column_exp”:”xiaocai”}* 被替換成了* {“_id”:ObjectId(“4d635ba2d549a02801000003″),”column_exp”:”HHHHHHHHH”,”column_fid”:123}*///** 批次更新 **/$where=array(‘column_name’=>’col’);$newdata=array(‘column_exp’=>’multiple’,’91u’=>684435);$result=$collection->update($where,array(‘$set’=>$newdata),array(‘multiple’=>true));/*** 所有’column_name’=‘col’都被修改*///** 自動累加 **/$where=array(’91u’=>684435);$newdata=array(‘column_exp’=>’edit’);$result=$collection->update($where,array(‘$set’=>$newdata,’$inc’=>array(’91u’=>-5)));/*** 更新91u=684435的資料,並且91u自減5*/ |
PHP操作MongoDB 資料庫總結記錄
5,刪除記錄操作
| //** 刪除節點 **/$where=array(‘column_name’=>’col685′);$result=$collection->update($where,array(‘$unset’=>’column_exp’));/*** 刪除節點column_exp*//** ** 完整格式:update(array $criteria, array $newobj [, array $options = array() ] )* 注意:1.注意區分替換更新與修改更新* 2.注意區分資料類型如 array(’91u’=>’684435′)與array(’91u’=>684435)* **///** 清空表 **/$collection->remove(); #清空集合//** 刪除指定MongoId **/$id = new MongoId(“4d638ea1d549a02801000011″);$collection->remove(array(‘_id’=>(object)$id)); |
6,查詢資料記錄
| //** 統計表記錄數 **/echo ‘count:’.$collection->count().”<br>”; #全部echo ‘count:’.$collection->count(array(‘type’=>’user’)).”<br>”; #統計‘type’ 為 user 的記錄echo ‘count:’.$collection->count(array(‘age’=>array(‘$gt’=>50,’$lte’=>74))).”<br>”; #統計大於50小於等於74echo ‘count:’.$collection->find()->limit(5)->skip(0)->count(true).”<br>”; #獲得實際返回的結果數/*** 注:$gt為大於、$gte為大於等於、$lt為小於、$lte為小於等於、$ne為不等於、$exists不存在*///** 擷取表中所有記錄 **/$cursor = $collection->find()->snapshot();foreach ($cursor as $id => $value) {echo “$id: “; var_dump($value); echo “<br>”;}/*** 注意:* 在我們做了find()操作,獲得$cursor遊標之後,這個遊標還是動態.* 換句話說,在我find()之後,到我的遊標迴圈完成這段時間,如果再有合格記錄被插入到collection,那麼這些記錄也會被$cursor 獲得.* 如果你想在獲得$cursor之後的結果集不變化,需要這樣做:* $cursor = $collection->find();*///** 查詢一條資料 **/$cursor = $collection->findOne();/*** 注意:findOne()獲得結果集後不能使用snapshot(),fields()等函數;*///** 設定顯示欄位 age,type 列不顯示 **/$cursor = $collection->find()->fields(array(“age”=>false,”type”=>false));$cursor = $collection->find()->fields(array(“user”=>true)); //只顯示user 列/*** 我這樣寫會出錯:$cursor->fields(array(“age”=>true,”type”=>false));*///** 設定條件 (存在type,age節點) and age!=0 and age<50 **/$where=array(‘type’=>array(‘$exists’=>true),’age’=>array(‘$ne’=>0,’$lt’=>50,’$exists’=>true));$cursor = $collection->find($where);//** 分頁擷取結果集 **/$cursor = $collection->find()->limit(5)->skip(0);//** 排序 **/$cursor = $collection->find()->sort(array(‘age’=>-1,’type’=>1)); ##1表示降序 -1表示升序,參數的先後影響排序次序//** 索引 **/$collection->ensureIndex(array(‘age’ => 1,’type’=>-1)); #1表示降序 -1表示升序$collection->ensureIndex(array(‘age’ => 1,’type’=>-1),array(‘background’=>true)); #索引的建立放在後台運行(預設是同步運行)$collection->ensureIndex(array(‘age’ => 1,’type’=>-1),array(‘unique’=>true)); #該索引是唯一的/*** ensureIndex (array(),array(‘name’=>’索引名稱’,‘background’=true,’unique’=true))* 詳見:http://www.php.net/manual/en/mongocollection.ensureindex.php*///** 取得查詢結果 **/$cursor = $collection->find();$array=array();foreach ($cursor as $id => $value) {$array[]=$value;} |
7.關閉連結 $conn->close(); #關閉串連 8,常見函數使用 a.$inc 如果記錄的該節點存在,讓該節點的數值加N;如果該節點不存在,讓該節點值等於N 設結構記錄結構為 array(’a’=>1,’b’=>’t’),想讓a加5,那麼: $coll->update(array(’b’=>’t’),array(’$inc’=>array(’a’=>5))) b.$set 讓某節點等於給定值 設結構記錄結構為 array(’a’=>1,’b’=>’t’),b為加f,那麼: $coll->update(array(’a’=>1),array(’$set’=>array(’b’=>’f’))) c.$unset 刪除某節點 設記錄結構為 array(’a’=>1,’b’=>’t’),想刪除b節點,那麼: $coll->update(array(’a’=>1),array(’$unset’=>’b’)) d.$push 如果對應節點是個數組,就附加一個新的值上去;不存在,就建立這個數組,並附加一個值在這個數組上;如果該節點不是數組,返回錯誤。 設記錄結構為array(’a’=>array(0=>’haha’),’b’=& gt;1),想附加新資料到節點a,那麼: $coll->update(array(’b’=>1),array(’$push’=>array(’a’=>’wow’))) 這樣,該記錄就會成為:array(’a’=>array(0=>’haha’,1=>’wow’),’b’=>1) e.$pushAll 與$push類似,只是會一次附加多個數值到某節點 f.$addToSet 如果該階段的數組中沒有某值,就添加之 設記錄結構為array(’a’=>array(0=& gt;’haha’),’b’=>1),如果想附加新的資料到該節點a,那麼: $coll->update(array(’b’=>1),array(’$addToSet’=>array(’a’=>’wow’))) 如果在a節點中已經有了wow,那麼就不會再添加新的,如果沒有,就會為該節點添加新的item——wow。 g.$pop 設該記錄為array(’a’=>array(0=>’haha’,1=>’wow’),’b’=>1) 刪除某數組節點的最後一個元素: $coll->update(array(’b’=>1),array(’$pop=>array(’a’=>1))) 刪除某數組階段的第一個元素 $coll->update(array(’b’=>1),array(’$pop=>array(’a’=>-1))) h.$pull 如果該節點是個數組,那麼刪除其值為value的子項,如果不是數組,會返回一個錯誤。 設該記錄為 array(’a’=>array(0=>’haha’,1=>’wow’),’b’=>1),想要刪除a中value為 haha的子項: $coll->update(array(’b’=>1),array(’$pull=>array(’a’=>’haha’))) 結果為: array(’a’=>array(0=>’wow’),’b’=>1) i.$pullAll 與$pull類似,只是可以刪除一組合格記錄。
PHP操作MongoDB 資料庫