<?php
include_once(path_format('config/config.php'));
class Mongo {
private $tag = "Mongodb";
private $mongodb='';
private $db='';
private $table='';
private $filter=[];
private $option=[];
public function connect($config){
try {
//实例化mongodb对象
$this->mongodb = new \MongoDB\Driver\Manager("mongodb://".$config['username'].":".$config['password']."@".$config['host'].":".$config['port']);
//无密码 $this->mongodb = new \MongoDB\Driver\Manager("mongodb://".$config['host'].":".$config['port']);
//库
$this->db=$config['dbname'];
return true;
} catch (Exception $e) {
Config::$logger->error($this->tag, "mongodb not connect : " . $e->getMessage());
return false;
}
}
public function close(){
$this->mongodb = null;
$this->db = null;
$this->table = null;
$this->filter = null;
$this->option = null;
return true;
}
//返回原生mongodb对象
public function mongodb(){
return $this->mongodb;
}
//设置操作表
public function table($table){
$this->table=$table;
return $this;
}
//条件
public function where($where){
if(is_string($where['_id'])){
$where['_id']=new \MongoDB\BSON\ObjectID($where['_id']);
}
$this->filter=$where;
return $this;
}
//分页
public function page($page,$num=10){
// $option['sort']=['ts'=>1];
$option['limit']=$num;
$option['skip']=($page-1)*$num;
$this->option=array_merge($this->option,$option);
return $this;
}
//排序
public function sort($sort=['_id'=>1]){
$option['sort']=$sort;
$this->option=array_merge($this->option,$option) ;
return $this;
}
//添加记录
public function insert($arr){
try {
$bulk = new \MongoDB\Driver\BulkWrite;
$bulk->insert($arr);
return $this->mongodb->executeBulkWrite($this->db.'.'.$this->table, $bulk)->getInsertedCount();
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
Config::$logger->error($this->tag, "mongodb not insert : " . $e->getWriteResult()->getWriteErrors());
return false;
}
}
//添加多条记录
public function insertMany($arrs){
try {
$bulk = new \MongoDB\Driver\BulkWrite;
foreach ($arrs as $arr){
$bulk->insert($arr);
}
return $this->mongodb->executeBulkWrite($this->db.'.'.$this->table, $bulk)->getInsertedCount();
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
Config::$logger->error($this->tag, "mongodb not insertMany : " . $e->getWriteResult()->getWriteErrors());
return false;
}
}
//删除记录
public function delete(){
try {
$bulk = new \MongoDB\Driver\BulkWrite;
$filter=$this->filter;
$bulk->delete($filter);
return $this->mongodb->executeBulkWrite($this->db.'.'.$this->table, $bulk)->getDeletedCount();
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
Config::$logger->error($this->tag, "mongodb not delete : " . $e->getWriteResult()->getWriteErrors());
return false;
}
}
//修改记录
public function update($data){
try {
$bulk = new \MongoDB\Driver\BulkWrite;
$bulk->update($this->filter,['$set' => $data],['multi' => false, 'upsert' => false]);
$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
return $this->mongodb->executeBulkWrite($this->db.'.'.$this->table, $bulk, $writeConcern)->getModifiedCount();
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
Config::$logger->error($this->tag, "mongodb not delete : " . $e->getWriteResult()->getWriteErrors());
return false;
}
}
//查找一条记录
public function find(){
try {
$query = new \MongoDB\Driver\Query($this->filter);
$cursor = $this->mongodb->executeQuery($this->db.'.'.$this->table, $query);
foreach ($cursor as $document) {
$res[]=json_decode(json_encode($document),true);
}
return $res[0];
} catch (Exception $e) {
Config::$logger->error($this->tag, "mongodb not find : " . $e->getMessage());
return false;
}
}
//查找记录
public function select(){
try {
$query = new \MongoDB\Driver\Query($this->filter,$this->option);
$cursor = $this->mongodb->executeQuery($this->db.'.'.$this->table, $query);
foreach ($cursor as $document) {
$res[]=json_decode(json_encode($document),true);
}
return $res;
} catch (Exception $e) {
Config::$logger->error($this->tag, "mongodb not select : " . $e->getMessage());
return false;
}
}
//取一条记录并删除
public function findAndRemove(){
try {
$arr = [
'findAndModify'=>$this->table,
'query'=>$this->filter,
'remove'=>true
];
$cmd=new \MongoDB\Driver\Command($arr);
$cursor = $this->mongodb->executeCommand($this->db, $cmd);
return $cursor->toArray()[0]->value;
} catch (Exception $e) {
Config::$logger->error($this->tag, "mongodb not findAndRemove : " . $e->getMessage());
return false;
}
}
/**
* pipeline 参数
$match 条件匹配。
$addFields 增加新字段。
$count 该stage的文档总数。
$group 分组。
$limit 限制数量。
$skip 跳步。
$sort 排序。
$out 输出结果到集合。
$project 过滤字段。
聚合的表达式:
$sum 计算总和。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
$avg 计算平均值 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
$min 获取集合中所有文档对应值得最小值。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
$max 获取集合中所有文档对应值得最大值。 db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])
$push 在结果文档中插入值到一个数组中。 db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])
$addToSet 在结果文档中插入值到一个数组中,但不创建副本。 db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])
$first 根据资源文档的排序获取第一个文档数据。 db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])
$last 根据资源文档的排序获取最后一个文档数据 db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])
*/
public function aggregate($pipeline=array()){
try {
$arr = [
'aggregate' => $this->table,
'pipeline' => $pipeline,
// [
// ['$group' => ['_id' => null,'num'=>['$sum'=>1]]]
// // ['$group' => ['_id' => '$player_id', 'sum' => ['$sum' => '$tongji']]],
// // ['$sum' => ['_id' => '$player_id', 'sum' => ['$sum' => '$tongji']]],
// ],
'cursor' => new stdClass,
];
$cmd=new \MongoDB\Driver\Command($arr);
$cursor = $this->mongodb->executeCommand($this->db, $cmd);
foreach ($cursor as $document) {
$res[]=json_decode(json_encode($document),true);
}
return $res;
// return $cursor->toArray()[0]->n;
} catch (Exception $e) {var_dump($e->getMessage());
Config::$logger->error($this->tag, "mongodb not count : " . $e->getMessage());
return false;
}
}
//统计
public function count(){
try {
$arr = [
'count'=>$this->table,
'query'=>$this->filter
];
$cmd=new \MongoDB\Driver\Command($arr);
$cursor = $this->mongodb->executeCommand($this->db, $cmd);
return $cursor->toArray()[0]->n;
} catch (Exception $e) {
Config::$logger->error($this->tag, "mongodb not count : " . $e->getMessage());
return false;
}
}
//调用函数
public function func($func){
try {
$arr = [
"eval" => $func
];
$cmd=new \MongoDB\Driver\Command($arr);
$cursor = $this->mongodb->executeCommand($this->db, $cmd);
return $cursor->toArray()[0]->retval;
} catch (Exception $e) {
Config::$logger->error($this->tag, "mongodb not func : " . $e->getMessage());
return false;
}
}
}
?>
php7 操作mongodb类
最新推荐文章于 2024-05-07 22:30:00 发布