PHP使用MongoDB类操作MongoDB数据库总结

时间:2022-11-09 23:04:48

参考:https://www.php.net/manual/zh/class.mongodb-driver-manager.php

参考:https://www.zhaokeli.com/article/8574.html

Driver\Manager 入口文件,一般都要先实例化该类
Driver\BulkWrite 读写类,数据库的增、删、改都要先靠该类来实现
Driver\Query 查询类,MongoDB支持丰富的查询方式,所以单独拿出来组建了一个类
Driver\Cursor 返回结果类,其实就是一个Cursor类的一个对象,该类有内置的toArray()函数可以结果转换成数组形式的
BSON\ObjectID 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' => '',
'user' => '',
'passwords' => '',
'db' => 'test'
);
// MongoDB\Driver入口类
private $Manage;
function __construct()
{
try {
$this->Manage = new MongoDB\Driver\Manager("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 MongoDB\Driver\BulkWrite();
if (is_array(current($data))) {
foreach ($data as $key => $datum) {
$_id = new MongoDB\BSON\ObjectID();
$datum['_id'] = $_id;
$BulkWrite->insert($datum);
$_ids[] = $_id->oid;
}
} else {
$_id = new MongoDB\BSON\ObjectID();
$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 MongoDB\Driver\BulkWrite();
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 MongoDB\Driver\BulkWrite();
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 MongoDB\Driver\Query($filter);
$cursor=$this->Manage->executeQuery($this->config['db'].".".$collection,$Query);
return $cursor->toArray();
}
}