程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP操作MongoDB配置與學習筆記

PHP操作MongoDB配置與學習筆記

編輯:關於PHP編程

PHP操作MongoDB配置與學習筆記有需要的朋友可參考參考。Mongo主要解決的是海量數據的訪問效率問題,根據官方的文檔,當數據量達到50GB以上的時候,Mongo的數據庫訪問速度是MySQL的 10倍以上

2,安裝(windows only)
到官網下載對應的包
解壓到d:mongodb
創建d:mongodbdata放置數據文件

3,運行mongodb
d:mongodbbin下有一些可執行文件,其中mongod.exe是服務器端,mongo.exe是客戶端。
運行cmd,輸入
d:mongodbbin>mongod.exe -dbpath d:mongodbdata
服務器成功啟動

4,讓php支持MongoDB
下載php_mongo.dll,注意版本,php5.3.x應該支持v9的(有些老資料讓apache的下v6,其實要看看phpinfo後下載對應的版本);
修改php.ini,增加 extension = php_mongo.dll;
重啟apache.

 

 代碼如下 復制代碼

<?php
/**
 * 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()."<br>";                                          #全部
echo 'count:'.$collection->count(array('type'=>'user'))."<br>";                     #可以加上條件
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->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;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved