php串連MongoDB資料庫及CRUD操作詳解

來源:互聯網
上載者:User
前言

前面對MongoDB的操作一直是通過mongo用戶端進程,進行的操作。但是現實中,我們對MOngoDB資料的操作,往往是通過相應的程式實現的,如php、java或是Python等。那麼怎樣在php中操作MongoDB呢。其實很簡單,類似操作MySQL一樣,它們都是作為擴充模組載入到PHP中。
當然,首先得安裝MongoDB,win下安裝可以參考(http://blog.csdn.net/hsd2012/article/details/51279472),Linux下安裝可以參考(http://blog.csdn.net/hsd2012/article/details/51286495)。其次,得搭建php執行環境。因為我是在本地測試,使用的是win系統,故我使用了WampServer搭建php執行環境。 在PHP中配置MongoDB

在php.ini中配置MongoDB相當簡單,只需要添加如下代碼即可

extension=php_mongo.dll  

主要注意的是php_mongo.dll版本必須和當前php版本想對應。否則會出現不相容錯誤。
關於php_mongo.dll下載可以到http://pecl.php.net/package/mongo 上下載。裡面提供了很多版本可供選擇。
因為我在win32下使用php版本是5.5.12,如下圖:

故我下載了如下版本php_mongo.dll

備忘:(1)Thread safe’(安全執行緒)是運行在Apache上,以擴充模組PHP上,如果你以CGI的模式運行PHP,請選擇非安全執行緒模式(’ non-thread safe’)。(2)32位系統選擇,86結尾檔案,64選擇64結尾的檔案。
配置好之後,輸出phpinfo();可以看到如下效果,代表配置ok了。
在PHP中串連MongoDB

首先得開啟MongoDB服務,詳情可參考(http://blog.csdn.net/hsd2012/article/details/51279472)

我們都知道,在php中串連Mysql資料庫,我們可以使用Mysqli或者Pdo類,詳情可參考(http://blog.csdn.net/hsd2012/article/details/51130098),那麼串連MongoDB是否也有相應的類呢。答案是肯定得。這個類就是MongoClient。它是PHP 和 MongoDB 的連線管理員,負責於建立和管理串連。類的結構如下:

MongoClient {/* 常量 */const string VERSION ;const string DEFAULT_HOST = "localhost" ;const int DEFAULT_PORT = 27017 ;const string RP_PRIMARY = "primary" ;const string RP_PRIMARY_PREFERRED = "primaryPreferred" ;const string RP_SECONDARY = "secondary" ;const string RP_SECONDARY_PREFERRED = "secondaryPreferred" ;const string RP_NEAREST = "nearest" ;/* 屬性 */public boolean $connected = FALSE ;public string $status = NULL ;protected string $server = NULL ;protected boolean $persistent = NULL ;/* 方法 */public __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) ]] )public bool close ([ boolean|string $connection ] )public bool connect ( void )public array dropDB ( mixed $db )public MongoDB __get ( string $dbname )public static array getConnections ( void )public array getHosts ( void )public array getReadPreference ( void )public array getWriteConcern ( void )public bool killCursor ( string $server_hash , int|MongoInt64 $id )public array listDBs ( void )public MongoCollection selectCollection ( string $db , string $collection )public MongoDB selectDB ( string $name )public bool setReadPreference ( string $read_preference [, array $tags ] )public bool setWriteConcern ( mixed $w [, int $wtimeout ] )public string __toString ( void )}

有了上面的類,現在我們可以開始寫串連MongoDB的程式了

// 連結的伺服器$m = new MongoClient();// 選擇一個資料庫$db = $m->school;// 選擇一個集合( Mongo 的“集合”相當於關係型資料庫的“表”)$collection = $db->student;
在PHP中查詢MongoDB資料

在PHP的MongoDB擴充模組中,提供了MongoCollection來進行資料的CURD操作。首先我們來看一下MongoCollection結構

MongoCollection {/* 常量 */const int ASCENDING = 1 ;const int DESCENDING = -1 ;/* Fields */public MongoDB $db = NULL ;public integer $w ;public integer $wtimeout ;/* 方法 */public array aggregate ( array $pipeline [, array $options ] )public MongoCommandCursor aggregateCursor ( array $command [, array $options ] )public mixed batchInsert ( array $a [, array $options = array() ] )public __construct ( MongoDB $db , string $name )public int count ([ array $query = array() [, int $limit = 0 [, int $skip = 0 ]]] )public array createDBRef ( mixed $document_or_id )public bool createIndex ( array $keys [, array $options = array() ] )public array deleteIndex ( string|array $keys )public array deleteIndexes ( void )public array distinct ( string $key [, array $query ] )public array drop ( void )public bool ensureIndex ( string|array $key|keys [, array $options = array() ] )public MongoCursor find ([ array $query = array() [, array $fields = array() ]] )public array findAndModify ( array $query [, array $update [, array $fields [, array $options ]]] )public array findOne ([ array $query = array() [, array $fields = array() [, array $options = array() ]]] )public MongoCollection __get ( string $name )public array getDBRef ( array $ref )public array getIndexInfo ( void )public string getName ( void )public array getReadPreference ( void )public bool getSlaveOkay ( void )public array getWriteConcern ( void )public array group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )public bool|array insert ( array|object $a [, array $options = array() ] )public array[MongoCommandCursor] parallelCollectionScan ( int $num_cursors )public bool|array remove ([ array $criteria = array() [, array $options = array() ]] )public mixed save ( array|object $a [, array $options = array() ] )public bool setReadPreference ( string $read_preference [, array $tags ] )public bool setSlaveOkay ([ bool $ok = true ] )public bool setWriteConcern ( mixed $w [, int $wtimeout ] )static protected string toIndexString ( mixed $keys )public string __toString ( void )public bool|array update ( array $criteria , array $new_object [, array $options = array() ] )public array validate ([ bool $scan_data = FALSE ] )}

可以發現,MongoCollection提供的方法中,很多方法和之前我們通過Mongo.exe進程操作資料的方法還是差不多的。通過Mongo.exe進程操作資料可以參考這裡(http://blog.csdn.net/hsd2012/article/details/51285831)。
現在,我們先看看本地mongoDB中的資料。
我們可以發現,school資料庫中,student集合中存在很多資料,如下圖:

現在我要檢索stu_id在15到22之間的所有資料
在命令提示字元中,我們可以如下操作:

在php程式中,我們可如下操作

// 連結的伺服器$m = new MongoClient();// 選擇一個資料庫$db = $m->school;// 選擇一個集合( Mongo 的“集合”相當於關係型資料庫的“表”)$collection = $db->student;$fruitQuery = array('stu_id' => array('$gte'=>15,'$lte'=>22)); //設定查詢條件$field=array('_id'=>0);//設定顯示欄位$res=$collection->find($fruitQuery,$field);foreach ($res as $stu) {    var_dump($stu);}

發現兩種操作資料的方式還是差不多的。只是php中不能直接使用json資料,如{name:”張三”},故使用數組方式去操作。 增加、修改、刪除MongoDB資料 增加資料

// 連結的伺服器$m = new MongoClient();// 選擇一個資料庫$db = $m->school;// 選擇一個集合( Mongo 的“集合”相當於關係型資料庫的“表”)$collection = $db->student;$data=array("stu_name"=>"李1","set"=>1,"class_id"=>5,"hobby"=>array("football","basketball"));$res=$collection->insert($data);var_dump($res);

修改資料

修改集合student中資料,程式如下:

// 連結的伺服器$m = new MongoClient();// 選擇一個資料庫$db = $m->school;// 選擇一個集合( Mongo 的“集合”相當於關係型資料庫的“表”)$collection = $db->student;//將stu_id為9的學生名字改“小李”$where=array('stu_id'=>9);$set=array('$set'=>array('class_name'=>3,'stu_name'=>'小李'));$options=array('upsert'=>0,'multiple'=>1);$rs=$collection->update($where,$set,$options);var_dump($rs);$res=$collection->findOne($where);var_dump($res);

刪除資料

刪除資料使用remove 方法,現在開始刪除stu_id為9的資料
代碼如下圖:

// 連結的伺服器$m = new MongoClient();// 選擇一個資料庫$db = $m->school;// 選擇一個集合( Mongo 的“集合”相當於關係型資料庫的“表”)$collection = $db->student;$where=array('stu_id'=>9);$rs=$collection->remove($where);var_dump($rs);$res=$collection->findOne($where);var_dump($res);

效果如下:
總結

通過php操作MongoDB資料的方法,可以發現,其實大多和通過mongo.exe操作資料是差不多的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.