参考:https://www.php.net/manual/zh/class.mongodb-driver-manager.php
参考:https://www.zhaokeli.com/article/8574.html
DriverManager 入口文件,一般都要先实例化该类
DriverBulkWrite 读写类,数据库的增、删、改都要先靠该类来实现
DriverQuery 查询类,MongoDB支持丰富的查询方式,所以单独拿出来组建了一个类
DriverCursor 返回结果类,其实就是一个Cursor类的一个对象,该类有内置的toArray()函数可以结果转换成数组形式的
BSONObjectID MongoDB默认创建的索引是_id,在添加的时候可以指定_id,给类就是可以创建一个指定内容的_id
我使用上述类简单操作MongoDB的时运行的顺序是:
实例化Manager类
要进行增删改操作时,实例化BulkWrite类,并根据需要的操作执行该类中的insert、delete、update方法,要进行查询时,实例化Query类
接着根据2中的操作,选择运行Manager类的executeQuery或者executeBulkWrite两个操作中的一个,返回结果类型是Cursor类,运行Cursor类的toArray方法,就能将结果从对象转换成数组,虽然其中还是会包含对象,但是比起单纯处理对象无疑是方便多了的。
这里贴一个基础操作类,把上面的过程进行了整合:
class MongoDBOperate { private $config = array( 'host' => '127.0.0.1', 'port' => '27017', 'user' => '', 'passwords' => '', 'db' => 'test' ); // MongoDBDriver入口类 private $Manage; function __construct() { try { $this->Manage = new MongoDBDriverManager("mongodb://" . $this->config['host'] . "/" . $this->config['port']); } catch (Exception $exception) { echo $exception->getMessage(); } } /** * @param $collection * @param $data * @return array * 新增数据 */ public function insert($collection, $data) { // 返回结果_id $_ids = array(); $BulkWrite = new MongoDBDriverBulkWrite(); if (is_array(current($data))) { foreach ($data as $key => $datum) { $_id = new MongoDBBSONObjectID(); $datum['_id'] = $_id; $BulkWrite->insert($datum); $_ids[] = $_id->oid; } } else { $_id = new MongoDBBSONObjectID(); $data['_id'] = $_id; $BulkWrite->insert($data); $_ids = $_id->oid; } $this->Manage->executeBulkWrite($this->config['db'] . "." . $collection, $BulkWrite); return $_ids; } /** * @param $collection * @param $filter * 删除数据 */ public function delete($collection,$filter){ $BulkWrite=new MongoDBDriverBulkWrite(); if(is_array(current($filter))){ foreach ($filter as $key=>$value){ $BulkWrite->delete($value); } }else{ $BulkWrite->delete($filter); } $this->Manage->executeBulkWrite($this->config['db'].".".$collection,$BulkWrite); } /** * @param $collection * @param $filter * @param $data * 更新数据 */ public function update($collection,$filter,$data){ $BulkWrite=new MongoDBDriverBulkWrite(); if(is_array(current($filter))){ foreach ($filter as $key=>$value){ $BulkWrite->update($value,$data[$key]); } }else{ // var_dump($filter); // var_dump($data); $BulkWrite->update($filter,$data); } $this->Manage->executeBulkWrite($this->config['db'].".".$collection,$BulkWrite); } /** * @param $collection * @param $filter * @return array * 查看数据 */ public function select($collection,$filter){ $Query=new MongoDBDriverQuery($filter); $cursor=$this->Manage->executeQuery($this->config['db'].".".$collection,$Query); return $cursor->toArray(); } }