php连接MongoDB数据库及CRUD操作详解

来源:互联网 发布:小轮公路车java 编辑:程序博客网 时间:2024/05/16 16:03

前言

前面对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操作数据是差不多的。

1 0
原创粉丝点击