php mongo 类,mongo php类
/**
* mongo 类
* User: wujp
* Date: 13-10-12
* Time: 下午5:48
*/
class Mongo_DB
{
#链接
public $conn = null;
#mongodb
public $db = null;
#链接参数
private $url = '';
#判断db是否链接
private $collected = null;
#查询、更新 映射 有|
private $four_map = array( #值是字符串,值不用处理
'>' => '$gt',
'>=' => '$gte',
' '$le',
'<=' => '$lte',
'!=' => '$ne',
'@' => '$exists', #键是否存在
'?' => 'perl', #正则
);
private $ele_map = array( #数组,值需要处理
'~' => '$elemMatch' #内嵌文档
);
private $log_map = array( #值必须是数组
'^' => '$in',
'!^' => '$nin',
'*' => '$all', #指定数组元素
);
#没有|
private $lgi_map = array( #必须是二维数组
'$' => '$or',
'&' => '$and',
);
private $where_map = array(
'%' => '$where', #javascript 函数
);
private $sort_map = array(
'DESC' => -1,
'ASC' => 1
);
#当前db下所有集合=>键数组
public $collections = null;
#基本配置参数
private $config = array(
'host' => 'localhost',
'port' => '27017',
'dbname' => '',
'user' => '',
'pass' => '',
'logpath' => '', #日志目录
'replicaset' => array( #集群
'host' => array()
// 'host' => array('host:port'), #主机群
// 'options' => array('readPreference', 'readPreferenceTags', 'replicaSet','slaveok')
),
);
/**
* 构造函数,基本参数设置
* @param $config
*
*/
public function __construct($config)
{
if (is_array($config) && $config) {
foreach ($this->config as $k => $v) {
if (isset($config[$k]) && $config[$k])
$this->config[$k] = !is_array($config[$k]) ? trim($config[$k]) : $config[$k];
}
$this->connect();
}
}
/**
* 初始化mongo
*
*/
private function connect()
{
if (!extension_loaded('mongo'))
exit('ERROR:MONGO EXTENSION NOT LOAD');
if ($this->conn === NULL) {
try {
if ($this->config['replicaset']['host']) {
#todo 主从配置,或者副本集,读扩展,
} else {
$this->url .= "mongodb://{$this->config['user']}:{$this->config['pass']}@{$this->config['host']}:
{$this->config['port']}/{$this->config['dbname']}";
$this->conn = new MongoClient($this->url);
}
$this->db = $this->conn->selectDB($this->config['dbname']);
if ($this->db) {
$this->collected = true;
$this->GetAllCollection(); #获取所有集合列表
}
} catch (MongoConnectionException $e) {
$this->ErrLog($e->getMessage());
exit('MONGO CONNECT ERROR');
}
}
}
/**
* 析构函数
*/
public function __destruct()
{
$this->collected = $this->collections = $this->db = $this->conn = null;
}
/**
* 获取db下所有集合名称
*
* @internal param $dbname
* @return bool
*/
private function GetAllCollection()
{
if (!$this->collected)
return false;
$colls = $this->db->listCollections();
if ($colls) {
foreach ($colls as $v) {
$pos = strpos($v, $this->config['dbname']);
if ($pos !== false)
$this->collections[] = substr($v, ($pos + strlen($this->config['dbname']) + 1));
}
return true;
} else {
return false;
}
}
/**
* 初始化集合对象
* @param $collname 集合名
* @return mixed
*/
public function GetMonCollection($collname)
{
if (!$this->collected)
return false;
return $this->db->selectCollection($collname);
}
/**
* 转换字符编码
* @param $array
* @return bool
*/
private function ConvertEncode($array)
{
if (is_array($array)) {
foreach ($array as &$v) {
if (is_array($v)) {
$v = $this->ConvertEncode($v);
if (!$v)
return false;
} else {
$code = mb_detect_encoding($v, array('UTF-8', 'ASCII', 'GB2312', 'GBK', 'CP936'), true);
if ($code !== 'UTF-8')
$v = mb_convert_encoding($v, 'UTF-8', $code);
}
}
return $array;
}
return false;
}
/**
* 获取where参数
* @param $where
* @param bool $type
* @return string
*
*/
private function GetWhere($where, $type = false)
{
$wheres = array();
$maps = array('four_map', 'log_map', 'ele_map');
$maps_np = array_merge($this->lgi_map, $this->where_map);
if (is_array($where) && $where) { #过滤查询条件
foreach ($where as $field => $val) {
$pos = strpos($field, '|');
if ($pos !== false) { #四则、正则、函数、数组、in、多重条件内嵌文档
$tep = substr($field, 0, $pos);
$key = substr($field, ($pos + 1));
if ($key !== false) {
foreach ($maps as $v) {
$arr = $this->$v;
if (in_array($tep, array_keys($arr))) {
if ($v == 'ele_map' && is_array($val))
$val = $this->GetWhere($val, true);
if ($tep == '?') { #正则
$val = new MongoRegex($val);
$wheres[$key] = $val;
} else {
$wheres[$key][$arr[$tep]] = $val;
}
}
}
}
} elseif (in_array($field, array_keys($maps_np))) {
if (in_array($field, array_keys($this->lgi_map)) && is_array($val)) { #逻辑
foreach ($val as $v) {
$val = $this->GetWhere($v, true);
$wheres[$maps_np[$field]][] = $val;
}
} else {
$wheres[$maps_np[$field]] = $val;
}
} else { #普通查询、单一条件内嵌文档
if (strpos($field, "[") !== false)
$field = str_replace("[", ".", $field);
if (is_array($val) && $type) {
$arr = $this->GetWhere($val);
foreach ($arr as $k => $v) {
$wheres[$k][] = $v;
}
} elseif (is_null($val)) {
$wheres[$field] = array('$in' => array(null), '$exists' => 1);
} else {
$wheres[$field] = $val; #支持 array('age'=>array('>'=>'18','<='=>'20'))
}
}
}
}
return $wheres;
}
/**
* 插入一行
* @param $collect
* @param $value
* @return bool
*/
public function InsOne($collect, $value)
{
if (!$this->collected || !is_array($value))
return false;
$id = array_search('id', array_keys($value)); #处理有id字段的情况
if ($id !== false && array_search('_id', array_keys($value)) === false) {
$value['_id'] = $value['id'];
unset($value['id']);
}
$value = $this->ConvertEncode($value);
if (!$value)
return false;
try {
$result = $this->GetMonCollection($collect)->insert($value);
$result = $result['err'] ? false : true;
} catch (MongoException $e) {
$this->ErrLog($e->getMessage());
return false;
}
return $result;
}
/**
* 插入多行
* @param $collect 集合
* @param $fields
* @param $values 键值对:array(0=>array(''=>''))
* @param bool $continueOnError 是否忽略插入错误,默认忽略
* @return bool
*/
public function InsMulit($collect, $fields, $values, $continueOnError = false)
{
if (!is_array($fields) || !is_array($values) || !$this->collected)
return false;
$id = array_search('id', $fields); #处理有id字段的情况
if ($id !== false && array_search('_id', $fields) === false)
$fields[$id] = '_id';
$data = array();
$values = $this->ConvertEncode($values);
if ($values) {
foreach ($values as $v) {
if (is_array($v)) {
$v = array_combine($fields, $v);
if ($v)
$data[] = $v;
}
}
}
if (!$data)
return false;
$option['continueOnError'] = $continueOnError ? true : false;
try {
$result = $this->GetMonCollection($collect)->batchinsert($data, $option);
$result = $result['err'] ? false : true;
} catch (MongoException $e) {
$this->ErrLog($e->getMessage());
return false;
}
return $result;
}
/**
* 查询一个
* @param $collect
* @param array $where
* @param $field string
* @return bool
*/
function FindOne($collect, $where = array(), $field)
{
if (!$this->collected)
return false;
$wheres = $this->GetWhere($where);
if ($where && !$wheres)
return false;
if (is_string($field) && trim($field))
$field = trim($field);
else
return false;
$result = $this->GetMonCollection($collect)->findOne($wheres, array($field));
if ($result) {
$arr = get_object_vars($result['_id']);
$result['_id'] = $arr['$id'];
return $result[$field];
}
return false;
}
/**
* 查询一条
* @param $collect
* @param array|string $where
* @param array $fields
* @param string $type
* @return array|bool
*/
function FindRow($collect, $where = array(), $fields = array(), $type = 'assoc')
{
if (!$this->collected)
return false;
$wheres = $this->GetWhere($where);
if ($where && !$wheres)
return false;
if ($fields && is_array($fields)) { #过滤fields
$val = '';
for ($i = 0; $i
$val[] = 1;
}
$fields = array_combine($fields, $val);
} else {
$fields = array();
}
$result = $this->GetMonCollection($collect)->findOne($wheres, $fields);
if ($result) {
if (in_array('_id', $fields)) {
$arr = get_object_vars($result['_id']);
$result['_id'] = $arr['$id'];
} else {
unset($result['_id']);
}
if (strtolower($type) == 'array')
$result = array_values($result);
return $result;
}
return false;
}
/**
* 复合查询 todo 查询高级选项扩展 snapshot maxscan min max hint explain
*
* $gt:>|$gte:>=|$le:
* array('x'=>array('$gt'=>'20'))
*
* $or:$|$end:&
* array('x'=>array('$in'=>array('1','2')))
*
* $where:%
* array('x'=>array('$where'=>function))
*
* 正则表达式:
* ?
*
* 数组:
* $all:*
*
* 内嵌文档:
* 单个条件:username.user username[user
* 多个条件:$elemMatch
*
* 逻辑操作符:
* not:!
* or:$
* end:&
* sort
* array('x'=>0)
*
* limit|skip
* $where = array('&|'=>array('she_hash' => '48b6c531ef2469469ede4ac21eebcf51', 'type' => 'doing'));
* $field = array('time', '_id' => 0);
* $res = $mongo->FindMix('sapilog', $where, $field,'1,2',array('time'=>'desc'));
* ------------------------->
* @param $collect |string
* @param string $where |array array('>|x'=>'10','<=|x'=>'20','^|x'=>array(),'%|x'=>'fun')
* @param array|string $fields |array|string 返回字段 默认为全部 字符串返回一个字段,键为数字则为返回该字段,键为字段,值为-1为不返回该字段
* @param string $limit |string skip,limit 0,10 如果没有 默认 skip为0 limit为当前变量
* @param string $sort |array array('x'=>'desc|asc') desc=>-1 asc=>
* @param string $type | string 返回类型 默认为关联数组 assoc|array
* @return bool
*/
public function FindMix($collect, $where = '', $fields = array(), $limit = '', $sort = '', $type = 'assoc')
{
if (!$this->collected)
return false;
$wheres = $this->GetWhere($where);
if ($where && !$wheres)
return false;
if ($fields && is_array($fields)) { #过滤fields
$val = '';
for ($i = 0; $i
$val[] = 1;
}
$fields = array_combine($fields, $val);
} else {
$fields = array();
}
$limits = '';
$skip = '';
if (is_string($limit)) { #过滤limit
$limit = explode(",", trim($limit));
if ($limit && is_numeric(implode('', $limit))) {
if (count($limit) == 1) {
$limits = $limit[0];
} else {
$skip = $limit[0];
$limits = $limit[1];
}
}
} elseif (is_numeric($limit)) {
$limits = trim($limit);
}
$sorts = '';
if (is_array($sort) && $sort) { #过滤sort
foreach ($sort as $k => $v) {
$k = trim($k);
$v = strtoupper(trim($v));
if (in_array($v, array_keys($this->sort_map))) {
$sorts[$k] = $this->sort_map[$v];
}
}
}
$result = $this->GetMonCollection($collect)->find($wheres, $fields);
if ($skip)
$result = $result->skip($skip);
if ($limits)
$result = $result->limit($limits);
if ($sorts)
$result = $result->sort($sorts);
if ($result) {
$return = array();
foreach ($result as $v) {
$return[] = $v;
}
foreach ($return as &$v) {
if (in_array('_id', $fields)) {
$arr = get_object_vars($v['_id']);
$v['_id'] = $arr['$id'];
} else {
unset($v['_id']);
}
if (strtolower($type) == 'array')
$v = array_values($v);
}
return $return;
}
return false;
}
/**
* 修改记录
* $inc、$set、$unset 修改普通文档,如果有就修改,没有就条件加值创建,前者只支持数字类型,使用后者,$unset删除元素
* $push、$addToSet 添加数组元素,前者不去重,使用后者
* $pop、$pull 删除数组元素,前者删除前后,后者删除指定元素,使用后者
*
* @param $collect
* @param $where
* @param $newdata |array
* @param string $type 操作类型 upd修改 unset删除指定元素 arr修改数组元素 pull删除数组元素
* @param bool $upsert 是否创建
* @param int $return |1:返回bool,2:返回影响行数
* @return bool
*/
public function UpdMix($collect, $where, $newdata, $type = 'upd', $upsert = false, $return = 1)
{
if (!$this->collected || !is_array($newdata))
return false;
$wheres = $this->GetWhere($where);
if (!$wheres) {
$this->ErrLog('where is error');
return false;
}
$newdata = $this->ConvertEncode($newdata);
$type = strtolower(trim($type));
$types = array('upd' => '$set', 'unset' => '$unset', 'arr' => '$addToSet', 'pull' => '$pull');
if (isset($types[$type])) {
$option = array();
if ($type == 'upd')
$option = array('multiple' => true);
if (in_array($type, array('upd', 'arr')) && $upsert)
$option['upsert'] = true;
$newdata = array($types[$type] => $newdata);
} else {
return false;
}
try {
$result = $this->GetMonCollection($collect)->update($wheres, $newdata, $option);
$result = $return == 1 ? ($result['err'] ? false : true) : $result['n'];
} catch (MongoConnectionException $e) {
$this->ErrLog($e->getMessage());
return false;
}
return $result;
}
#todo EXPLAIN 函数
/**
* 对集合执行命令
* @param $data
* @return bool
*/
public function RunCommand($data)
{
if (is_array($data) && $data && $this->collected) {
$result = $this->db->command($data);
if (isset($result['values']))
return $result['values'];
else
$this->ErrLog("command error,info:" . $result['errmsg'] . ",bad_cmd:" . json_encode($result['bad cmd']));
}
return false;
}
/**
* todo 聚合
*
*/
public function Group()
{
}
public function Count($collect, $where = array())
{
if (!$this->collected)
return false;
$wheres = $this->GetWhere($where);
if ($where && !$wheres)
return false;
return $this->GetMonCollection($collect)->count($wheres);
}
/**
* 返回指定键的唯一值列表
* @param $collect
* @param $key
* @param array $where 额外查询条件
* @return bool
*/
public function Distinct($collect, $key, $where = array())
{
if (!$this->collected)
return false;
$wheres = $this->GetWhere($where);
if ($where && !$wheres)
return false;
try {
$result = $this->GetMonCollection($collect)->distinct($key, $wheres);
} catch (MongoException $e) {
$this->ErrLog($e->getMessage());
return false;
}
return $result;
}
/**
* 删除集合中的记录
* @param $collect
* @param $where
* @param int $return 1:返回bool,2:返回影响行数
* @return bool
*/
public function RemoveColl($collect, $where, $return = 1)
{
if (!$this->collected)
return false;
$wheres = $this->GetWhere($where);
if (!$wheres) {
$this->ErrLog('where is error');
return false;
}
try {
$result = $this->GetMonCollection($collect)->remove($wheres);
$result = $return == 1 ? ($result['err'] ? false : true) : $result['n'];
} catch (MongoConnectionException $e) {
$this->ErrLog($e->getMessage());
return false;
}
return $result;
}
/**
* mongo 错误日志函数
*
* @param $msg
* @param int $lever
*
*/
private function ErrLog($msg, $lever = 2)
{
global $__CFG;
$trace = debug_backtrace();
$error_log = '';
$date = date("Ymd", time());
$line = isset($trace[$lever]['line']) ? trim($trace[$lever]['line']) : '';
$file = isset($trace[$lever]['file']) ? trim($trace[$lever]['file']) : '';
$object = isset($trace[$lever]['object']) ? get_class($trace[$lever]['object']) : '';
$args = isset($trace[$lever]['args']) ? json_encode($trace[$lever]['args']) : '';
$error_log .= "line {$line} " . ($object ? 'of ' . $object : '') . "(in {$file})\n";
$error_log .= $args ? "args:{$args}\n" : '';
$error_log .= "msg:{$msg}";
if (isset($__CFG['com']['id']) && $__CFG['com']['id']) {
$com_id = $__CFG['com']['id'];
} else {
$com_id = 'common';
}
$log_dir = $this->config['logpath'] ? $this->config['logpath'] : __ROOT__ . "data/nginx_error_log/{$com_id}/{$date}/mongo.nginx_error_log";
error_log("Date:" . date("Y-m-d H:i:s", $date) . "\nstamp:{$date}\ntrace:{$error_log}\n\n", 3, $log_dir);
if (isset($__CFG['currUser']) && $__CFG['currUser'] == 'root' && isset($__CFG['daemon']['user'])) {
$paths = explode("nginx_error_log/", $log_dir);
$pathc = explode("/", $paths[1]);
$pathd = $paths[0] . "nginx_error_log";
foreach ($pathc as $v) {
$pathd .= "/" . $v;
chgrp($pathd, $__CFG['daemon']['user']);
chown($pathd, $__CFG['daemon']['user']);
}
}
}
}
php mongo 类,mongo php类相关推荐
- python中的新式类与旧式类的一些基于descriptor的概念(上)
python中基于descriptor的一些概念(上) 1. 前言 2. 新式类与经典类 2.1 内置的object对象 2.2 类的方法 2.2.1 静态方法 2.2.2 类方法 2.3 新式类(n ...
- C++ 笔记(16)— 类和对象(类定义、类实例对象定义、访问类成员、类成员函数、类 public/private/protected 成员、类对象引用和指针)
1. 类的定义 类定义是以关键字 class 开头,后跟类的名称.并在它后面依次包含类名,一组放在 {} 内的成员属性和成员函数,以及结尾的分号. 类声明将类本身及其属性告诉编译器.类声明本身并不能改 ...
- java 类定义_JAVA类与对象(二)----类定义基础
类是组成java程序的基本要素,是java中的一种重要的复合数据类型.它封装了一类对象的状态和方法,是这一类对象的原型.一个类的实现包括两个部分:类声明和类体,基本格式: class { 属性 方法 ...
- C++派生类与基类构造函数调用次序
本文用来测试C++基类和派生类构造函数,析构函数,和拷贝构造函数的调用次序. 运行环境:SUSE Linux Enterprise Server 11 SP2 (x86_64) #include & ...
- python 类中定义类_Python中的动态类定义
python 类中定义类 Here's a neat Python trick you might just find useful one day. Let's look at how you ca ...
- Java 常用对象-Date类和Calender类
2017-11-02 22:29:34 Date类:类 Date 表示特定的瞬间,精确到毫秒. 在 JDK 1.1 之前,类 Date 有两个其他的函数.它允许把日期解释为年.月.日.小时.分钟和秒值 ...
- C++中基类与派生类的构造函数和析构函数
1.Cpp中的基类与派生类的构造函数 基类的成员函数可以被继承,可以通过派生类的对象访问,但这仅仅指的是普通的成员函数,类的构造函数不能被继承.构造函数不能被继承是有道理的,因为即使继承了,它的名字和 ...
- OpenCV 中的 Scalar 类、Vec类
转 自 http://www.bubuko.com/infodetail-1533054.html 文章目录 Scalar 类 Vec 类 Scalar 类 typedef Scalar_<do ...
- 友元类实例:日期类 学生类
1.定义Date类 : Date类中定义了三个私有数据成员(year ,month,day) 2.定义Student类: 在Student类中定义了两个私有数据成员(name[] ,birthday) ...
- 类的实质——类成员public、private属性的另类解释
一.基本思想: 计算机是执行程序的机器,程序是干活的.而函数.类则是具有一定功能的程序块,是干活的.函数和类的关系,就象基本电子元器件与集成块的关系一样,是程序块大小的问题,是大小的关系... 二.类 ...
最新文章
- 程序员必备技能:如何画好架构图?
- 后台开发经典书籍--计算机网络
- Vue前后台数据交互实例演示,使用axios传递json字符串、数组
- windows下的MySql实现读写分离
- Bootstrap浅色淡雅个人博客
- C51单片机————串行接口
- springAOP之代理
- 前端用户忘记密码,手机验证码修改密码功能
- ELK logstash基本配置
- 大学计算机基础题库百度云资源,《大学计算机基础试题题库及答案》.pdf
- 在vs2010中运行guge.cpp(SkeletonDepth)的时候程序是网上的,可是总是提示我没有KinectUNI.lib。
- T156基于51单片机LCD12864指针时钟Proteus设计、keil程序、c语言、源码、ds1302,电子时钟,62256
- 一篇读懂深度学习中「训练」和「推断」的区别
- 展望:2021年程序员业界趋势与生存指南
- 浙江大学计算机学院钱沄涛实验室,浙江大学导师介绍--钱沄涛
- VBA--遍历所有工作表,获取所有行和列,复制粘贴为数值
- python中cv2.putText参数详解
- ofo 破解 android ios 版 (类似 wifi 万*能*钥*匙 )
- 寻找鲁菜——美食江山寻味记之二·舜和品味
- 数据分析-建立回归模型的流程
热门文章
- C ++ 指针 | 指针与函数_7
- csh shell_一篇文章从了解到入门shell
- 江苏省计算机一级题库软件百度云,江苏省计算机一级B题库11
- Intel® Nehalem/Westmere架构/微架构/流水线 (6) - 读写操作Load/Store增强
- 为系统扩展而采取的一些措施——异步
- Coursera Machine Leaning 课程总结
- oracle 论坛 千万级表,Oracle千万级记录操作总结
- 使用ajax获取后台数据怎么打印,我用ajax获取后台数据并展示在前端页面的方法【源码】...
- 关于ddx/ddy重建法线在edge边沿上的artifacts问题
- UE3 虚幻编辑器控制台命令