qileilove

          blog已經轉移至github,大家請訪問 http://qaseven.github.io/

          PHP操作MongoDB 數據庫總結記錄

          最近有個項目,需要用php操作mongoDb數據,所以了解下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: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)); #完整
            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小于等于74
          echo ‘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類似,只是可以刪除一組符合條件的記錄。

          posted on 2014-05-29 11:22 順其自然EVO 閱讀(2082) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          <2014年5月>
          27282930123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          導航

          統計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 江油市| 台前县| 宁远县| 个旧市| 平山县| 萨嘎县| 邵阳市| 延川县| 安徽省| 利津县| 盈江县| 旬邑县| 珲春市| 墨江| 开鲁县| 都匀市| 吴旗县| 祁连县| 镇宁| 昆明市| 衡东县| 扎赉特旗| 东宁县| 九龙城区| 伽师县| 湖南省| 灌阳县| 和顺县| 噶尔县| 蛟河市| 师宗县| 鄂托克前旗| 琼海市| 罗源县| 泸定县| 历史| 孝义市| 东至县| 长垣县| 会理县| 崇州市|