/** * PHP操作MongoDB學習筆記 * 2011年2月23日 * 原作者:xiaocai */ //************************* //** 串連MongoDB資料庫伺服器 //************************* //格式=>("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:123@localhost"); #帶使用者名稱密碼 //$conn=new Mongo("mongodb://localhost:27017,localhost:27018"); #串連多個伺服器 //$conn=new Mongo("mongodb:///tmp/mongo-27017.sock"); #域通訊端 //$conn=new Mongo("mongodb://admin_miss:miss@localhost:27017/test",array('persist'=>'p',"replicaSet"=>true)); #完整 //************************* //** 選擇資料庫與表 //************************* $db=$conn->mydb; #選擇mydb資料庫 //$db=$conn->selectDB("mydb"); #第二種寫法 $collection=$db->column; #選擇集合(選擇'表') //$collection=$db->selectCollection('column'); #第二種寫法 //$collection=$conn->mydb->column; #更簡潔的寫法 //注意: // 1.資料庫和集合不需要事先建立,若它們不存在則會自動建立它們. // 2.注意錯別字,你可能會無意間的建立一個新的資料庫(與原先的資料庫混亂). //************************* //** 插入文檔 //************************* //**向集合中插入資料,返回bool判斷是否插入成功. **/ $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) #插入結果:{ "_id" : ObjectId("4d63552ad549a02c01000009"), "column_name" : "col770", "column_exp" : "xiaocai" } #'_id'為主鍵欄位,在插入是MongoDB自動添加. //**向集合中安全插入資料,返回插入狀態(數組). **/ $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) } //**插入的完整文法 **/ # insert(array $data,array('safe'=>false,'fsync'=>false,'timeout'=>10000)) # 參數說明:safe:預設false,是否安全寫入;fsync:預設false,是否強制插入到同步到磁碟;timeout:逾時時間(毫秒) //**以下兩次插入的為同一條記錄(相同的_id),因為它們的值相同**/ $collection->insert(array('column_name'=>'xiaocai')); $collection->insert(array('column_name'=>'xiaocai')); #避免方法,安全插入 $collection->insert(array('column_name'=>'xiaocai'),true); try { $collection->insert(array('column_name'=>'xiaocai'),true); }catch(MongoCursorException $e){ echo "Can't save the same person twice!n"; } //詳細資料:http://www.php.net/manual/zh/mongocollection.insert.php //************************* //** 更新文檔 //************************* //** 修改更新 **/ $where=array('column_name'=>'col123'); $newdata=array('column_exp'=>'GGGGGGG','column_fid'=>444); $result=$collection->update($where,array('$set'=>$newdata)); #$set:讓某節點等於給定值 /* * 原資料 * {"_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 * 注意:91u存在時加上-5,不存在時就設定91u=-5 */ //** 匹配到就更新,否則新增 **/ $c->update( array("name" => "joe"), array("username" => "joe312", "createdAt" => new MongoDate()), array("upsert" => true) #up(date)(in)sert ); /** 刪除節點 **/ $where=array('column_name'=>'col685'); $result=$collection->update($where,array('$unset'=>'column_exp')); /** * 刪除節點column_exp */ /** 附加新資料到節點 **/ $coll->update( array('b'=>1), array('$push'=>array('a'=>'wow')) #附加新資料到節點a ); # 如果對應節點是個數組,就附加一個新的值上去;不存在,就建立這個數組,並附加一個值在這個數組上; # 如果該節點不是數組,返回錯誤。 # 原紀錄:array('a'=>array(0=>'haha'),'b'=>1) # 新記錄為:array('a'=>array(0=>'haha',1=>'wow'),'b'=>1) # $pushAll與$push類似,只是會一次附加多個數值到某節點 /** 判斷更新 **/ $coll->update( array('b'=>1), array('$addToSet'=>array('a'=>'wow')) ); # 如果該階段的數組中沒有某值,就添加之 # 設記錄結構為array('a'=>array(0=>'haha'),'b'=>1) # 如果在a節點中已經有了wow,那麼就不會再添加新的, # 如果沒有,就會為該節點添加新的item——wow。 /** 刪除某數組節點的最後一個元素 **/ $coll->update( array('b'=>1), array('$pop'=>array('a'=>1)) #刪除a數組節點的最後一個元素 ); /** 刪除某數組節點的第一個元素 **/ $coll->update( array('b'=>1), array('$pop'=>array('a'=>-1)) #刪除a數組節點的第一個元素 ); /** 刪除某數組節點的元素 **/ $coll->update( array('b'=>1), array('$pull'=>array('a'=>'haha')) ) # 如果該節點是個數組,那麼刪除其值為value的子項,如果不是數組,會返回一個錯誤。 # 原記錄為:array('a'=>array(0=>'haha',1=>'wow'),'b'=>1), # 刪除a中value為haha的子項 # 結果為: array('a'=>array(0=>'wow'),'b'=>1) # $pullAll與$pull類似,只是可以刪除一組合格記錄。 # 注意: # 1.注意區分替換更新與修改更新 # 2.注意區分資料類型如 array('91u'=>'684435')與array('91u'=>684435) //************************* //** 刪除文檔 //************************* /** 刪除 **/ $collection->remove(array('column_name'=>'col399')); //$collection->remove(); #清空集合 //$collection->drop(); #清空,效率高於remove() /** 刪除指定MongoId **/ $id = new MongoId("4d638ea1d549a02801000011"); $collection->remove(array('_id'=>(object)$id)); /* * * * 使用下面的方法來匹配{"_id":ObjectId("4d638ea1d549a02801000011")},查詢、更新也一樣 * $id = new MongoId("4d638ea1d549a02801000011"); * array('_id'=>(object)$id) * * */
//************************* //** 查詢文檔 //*************************
/** 查詢文檔中的記錄數 **/ echo 'count:'.$collection->count()." "; #全部 echo 'count:'.$collection->count(array('type'=>'user'))." "; #可以加上條件 echo 'count:'.$collection->count(array('age'=>array('$gt'=>50,'$lte'=>74)))." "; #大於50小於等於74 echo 'count:'.$collection->find()->limit(5)->skip(0)->count(true)." "; #獲得實際返回的結果數 /** * 注:$gt為大於、$gte為大於等於、$lt為小於、$lte為小於等於、$ne為不等於、$exists不存在 */ /** 集合中所有文檔 **/ $cursor = $collection->find()->snapshot(); foreach ($cursor as $id => $value) { echo "$id: "; var_dump($value); echo " "; } /** * 注意: * 在我們做了find()操作,獲得$cursor遊標之後,這個遊標還是動態. * 換句話說,在我find()之後,到我的遊標迴圈完成這段時間,如果再有合格記錄被插入到collection,那麼這些記錄也會被$cursor獲得. * 如果你想在獲得$cursor之後的結果集不變化,需要這樣做: * $cursor = $collection->find(); * $cursor->snapshot();#獲得快照! * 詳見http://www.bumao.com/index.php/2010/08/mongo_php_cursor.html */ /** 查詢一條資料 **/ $cursor = $collection->findOne(); /** * 注意:findOne()獲得結果集後不能使用snapshot(),fields()等函數; */ /** age,type 列不顯示 **/ $cursor = $collection->find()->fields(array("age"=>false,"type"=>false)); /** 只顯示user 列 **/ $cursor = $collection->find()->fields(array("user"=>true)); /** * 我這樣寫會出錯:$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)); #該索引是唯一的 /** 取得查詢結果 **/ $cursor = $collection->find(); $array=array(); foreach ($cursor as $id => $value) { $array[]=$value; } |