php mongodb操作类

<?php

namespace common\helpers;
use yii;
use MongoDB\Driver\Manager;
use MongoDB\Collection;

class MyMongo{
public $mongoClient;
public $table='';
public $db='gscf';
public function __construct(){
if(!$this->mongoClient instanceof \MongoClient){
try {
$this->mongoClient=new \MongoDB\Client(Yii::$app->params['mongo'][YII_ENV]['server']);
}catch (\Exception $e){
echo $e->getMessage().'<br/>'; exit;
}
}
$this->setDB(Yii::$app->params['mongo'][YII_ENV]['database']);
return $this->mongoClient;
}

/**
* @param $db
* @return \MongoDB\Database
*/
public function setDB($db){
$this->db=$db;
return $this->mongoClient->{$this->db};
}

/**
* @param $table
* @return Collection
*/
public function setTable($table){
$this->table=$table;
return $this->mongoClient->{$this->db}->{$this->table};
}

/**
* 插入一条数据
* @param $tableName
* @param $data
* @return int
*/
public function insertOne($tableName,$data){
$obTable = $this->setTable($tableName);
try{
$insertResult = $obTable->insertOne($data);
return $insertResult->getInsertedCount();
}catch (\Exception $e){
// echo $e->getMessage().'<br/>'; exit;
return '';
}
}

/**
* 插入多条数据
* @param $tableName
* @param $data
* @return array (count 插入条数 id_list 插入id编号列表)
*/
public function insertMore($tableName,$data){
$obTable = $this->setTable($tableName);
try{
$insertResult = $obTable->insertMany($data);
$count = $insertResult->getInsertedCount();
$returnIdList = [];
if ($count>0){
foreach($insertResult->getInsertedIds() as $val){
$returnIdList[] = (string)$val;
}
}
return ['count'=>$count,'id_list'=>$returnIdList];
}catch (\Exception $e){
// echo $e->getMessage().'<br/>'; exit;
return '';
}

}
/**
* 更新记录
* @param $tableName
* @param $where
* @param $data
* @param $status 1为更新单条 2为更新多条
* @return array
*/
public function updateData($tableName,$where,$data,$status=1){
$obTable = $this->setTable($tableName);
try{
if(1 == $status){
$obUpdate = 'updateOne';
}else{
$obUpdate = 'updateMany';
}
$updateResult = $obTable->$obUpdate($where,['$set'=>$data]);
return ['matched_count'=> $updateResult->getMatchedCount(),'modified_count'=>$updateResult->getModifiedCount()];
}catch (\Exception $e){
// echo $e->getMessage().'<br/>'; exit;
return '';
}
}

/**
* 创建索引
* @param $tableName
* @param $indexArr
* @return string
*/
public function createIndex($tableName,$indexArr){
$obTable = $this->setTable($tableName);
try{
return $obTable->createIndex($indexArr);
}catch (\Exception $e){
// echo $e->getMessage().'<br/>'; exit;
return '';
}
}

/**
* 删除索引
* @param $tableName
* @param $key
* @return array|object|string
*/
public function dropIndex($tableName,$key){
$obTable = $this->setTable($tableName);
try{
return $obTable->dropIndex($key);
}catch (\Exception $e){
// echo $e->getMessage().'<br/>'; exit;
return '';
}
}
/**
* 删除数据
* @param $tableName
* @param $where
* @param int $status 1为删除单条 2为删除多条
* @return array
*/
public function deleteData($tableName,$where,$status=1){
$obTable = $this->setTable($tableName);
try{
if(1 == $status){
$obDelete = 'deleteOne';
}else{
$obDelete = 'deleteMany';
}
$deleteResult = $obTable->$obDelete($where);
return ['matched_count'=> $deleteResult->getDeletedCount()];
}catch (\Exception $e){
// echo $e->getMessage().'<br/>'; exit;
return '';
}
}

/**
* 查询一条数据
* @param $tableName
* @param $where
* @return array|null|object
*/
public function findOne($tableName,$where){
$obTable = $this->setTable($tableName);
try{
$result = $obTable->findOne($where);
return $this->object_array($result);
}catch (\Exception $e){
// echo $e->getMessage().'<br/>'; exit;
return '';
}
}
/**
* 查询更多
* @param $tableName
* @param $condition ['where'=>[],'screen'=>[]] where为查询条件 screen其他条件
* 例:
$condition = [
'where' => [
'_id' => ['$gt'=>1],
'name' => 'Admin User',
'add_time' => ["$gte"=>1111,"$lte"=>222]
],
'screen'=> [
'limit' => 2,//显示条数
'sort' => [
'_id' => -1//1正序 -1 倒序
],
'projection' => [//限定调用字段[当里面字段的值有1的情况下只显示为1的字段内容(注意:_id特殊,在有1的情况下,不设定_id的值为1也会显示)]
'_id' => 1,
'username' => 1,
'email' => 1
],
'skip' => 3,//跳过数据
],
];
//注意:where条件的类型要和Mongodb一致 skip无法跳过过多数据,使用aggregate
$result = $mg->findMore('tender_custody_log_test',$condition);//查询多条记录
*
* @return array
*/
public function findMore($tableName,$condition){
$obTable = $this->setTable($tableName);
if(!isset($condition['where'])){
$condition['where'] = [];
}
if(!isset($condition['screen'])){
$condition['screen'] = [];
}
try{
$result = $obTable->find($condition['where'],$condition['screen']);
$returnArr = [];
foreach ($result as $document) {
$returnArr[] = $this->object_array($document);
}
return $returnArr;
}catch (\Exception $e){
// echo $e->getMessage().'<br/>'; exit;
return '';
}
}

/**
* 统计总数
* @param $tableName
* @param $condition 注意:条件后面如果是数字,类型必须int转换后才可使用
* @return int
*/
public function count($tableName,$condition){
$countCondition = isset($condition['where'])?$condition['where']:[];
$obTable = $this->setTable($tableName);
//db.tender_user_log.aggregate([{$match:{add_time:{$gt:1531213200}}},{$group:{_id:"",total:{$sum:1}}}])
$result = $obTable->count($countCondition);
return $result;
}

/**
* 分组聚合查询记录
* @param $tableName
* @param $pipe
* 示例:
* $pipe = [
[
'$match' => [
'age' => ['$gte'=>17],
],
],
[
'$sort' => [
'add_time' =>['$gte'=>111,'$lte'=>222],
],
],
[
'$group' => [
'_id' => ['sex'=>'$sex'],'count' => array('$sum' => 1),
],
],
[
'$project' => [//显示字段,显示的字段为$group中的字段
'sex' => '$_id.sex',
'count' => '$count',
]
],
[
'$skip' => $getLimit['skip']
],
[
'$limit' => $getLimit['limit']
],
];
类似mysql语句:select sex,count(*) as count from table where age>=17
like 使用 new Regex($getCondition['params']['like'],'i')
$group['_id']['count']['$sum'] 对应值说明:[1:count,$ziduan:求和字段]
$group['_id']['count']['---']其他参考Mongo手册
注意:$pipe 中的$match、$group、$project的顺序不能反过来使用
and 与OR用法展示
$or = [
['username' => new Regex('测试','i')],
['uid' => (int)'测试'],
['account' => '测试']
];
$match['$match']['$or'] = $or;
$and= [
['add_time'=>['$gte'=>'2011-11-11 11:11:11','$lte'=>'2012-11-11 11:11:11']],
['a'=>1]
];
$match['$match']['$and'] = $and;
* @return \Traversable
*/
public function groupData($tableName,$pipe){
// db.tender_custody_log_test.aggregate([{$match:{_id:{$gt:7}}},{$group:{_id:"",total:{$sum:1}}},{$sort:{total:-1}}])
$obTable = $this->setTable($tableName);
$cursor = $obTable->aggregate($pipe);
$returnArr = [];
foreach ($cursor as $value) {
$returnArr[]=$this->object_array($value);
}
return $returnArr;
}
public function getMoreList($tableName,$pipe){

}
//PHP stdClass Object转array
private function object_array($array) {
if(is_object($array)) {
$array = (array)$array;
} if(is_array($array)) {
foreach($array as $key=>$value) {
if(is_object($value)){
$value = $this->object_array($value);
}
$array[$key] =$value;
}
}
return $array;
}
}

posted on 2018-07-10 18:21  我很迷茫  阅读(1004)  评论(0)    收藏  举报