<?php
/**
* Mongodb 基本操作API,支持基本类似关系统型数据库的操作接口
*
* @author rong.xiang@ronghai.com
* @version 0.36
*
* [说明]
*
* 1:该版本API实现了 Mongodb 中最基本的插入/修改/查询/删除操作的封装
* 2:其它更高级的操作可通过 $this->getMongo() 得到原生的对象
* 3:该类所有API接口中的 $query 查询参数的使用请以下有关 [查询条件说明文档]
* 4: 如果要存储中文字符,则一定要使用 utf8 的编码.
* 5:有了本类接口基本可以按关系型数据库的概念完成Mongodb的大部分开发操作
* 6: 读写分离
* 7: distinct支持
* 8: 多读一写的设置
* 9: count修复
* 10: insert 成功不返回true 而是_id
*
* [查询条件说明文档]
*
* 参数:array('id'=>1)
* 等同:where id=1
*
* 参数:array('id'=>1,'num'=>10)
* 等同:where id=1 and num=10
*
* 参数:array('id'=>array($mongo->cmd('>')=>5))
* 等同:where id>5
*
* 参数:array('id'=>array($mongo->cmd('!=')=>5))
* 等同:where id!=5
*
* 参数:array('id'=>array($mongo->cmd('>')=>5, $mongo->cmd('<')=>10))
* 等同:where id>5 and id<10
*
* 参数:array('id'=>array($mongo->cmd('in')=>array(2,5,6)))
* 等同:where id in (2,5,6)
*
* 参数:array('id'=>array($mongo->cmd('%')=>array(2,1)))
* 等同:where id % 2 = 1
*
* 参数:array($mongo->cmd('or') => array( array('id'=>array($mongo->cmd('>')=>5)), array('id'=>array($mongo->cmd('<')=>10)) ) )
* 等同:where id>5 or id<10
*
**/
class xMongo224{
/**
* Mongodb 对象句柄
*
* @var object Mongo
*/
private $_host_read = array('mongodb://username:password@serverip');
private $_host_write = 'mongodb://username:password@serverip';
private $_mongo_read = null;
private $_mongo_write = null;
/**
* 当前选择的数据库
*
* @var object MongoDB
*/
private $_db = null;
/**
* 修改器命令前缀
*
* @var string
*/
private $_cmd = '$';
/**
* 查询条件映射关系
*
* @var array
*/
private $_condMap = array(
'<'=>'lt', // id > 1
'<='=>'lte', // id <= 10
'>'=>'gt', // id > 5
'>='=>'gte', // id >= 4
'!='=>'ne', // id != 4
'%'=>'mod', // id % 4 = 0
'in'=>'in', // id in (1,2,3,4)
'notin'=>'nin',// id not in (1,2,3,4)
'or'=>'or', // id=1 or id=2
'not'=>'not', // !(id=1)
);
/**
* 构造函数
*
* @param array $config 服务器配置,默认为:
* array(
* 'host'=>'localhost', // 主机名或IP地址
* 'port'=>27017, // 端口
* 'cmd'=>'$', // 修改器命令前缀
* )
*/
public function __construct(){
if (!extension_loaded('mongo')) {
exit('The mongo extension must be loaded!');
}
/*
$this->_mongo_read = new mongo($this->_host_read);
$this->_mongo_write = new mongo($this->_host_write);
$this->_cmd = ini_get('mongo.cmd');
if($this->_cmd == ''){
$this->_cmd = '$';
}
*/
}
/* ==================================== 基本操作接口API ================================= */
/**
* 向集合(表)中插入新文档
*
* 说明:
* 1:类似mysql中的: insert into $colName set id=1,name='name1';
*
* @param string $colName 集合名
* @param array $sets 数据,如: array('id'=>1,'name'=>'name1')
* @param boolean $safe 是否安全操作 false:不等待服务器的响应直接返回 true:等待服务器的响应(数据非常重要时推荐)
* @param boolean $fsync 操作后是否立即更新到碰盘,默认情况下由服务器决定
*
* @return boolean
*/
public function insert($colName, $sets, $safe=false, $fsync=false){
$col = $thi
mongodb的操作类,实现一写多读分离
最新推荐文章于 2021-03-17 22:23:42 发布
这是一个PHP类,用于封装MongoDB的基本操作,支持读写分离,多读一写设置,以及distinct和count等功能。类中包含插入、更新、删除、查询等方法,提供类似于SQL的操作接口,方便进行数据操作。同时,类还处理了_id字段的转换,以适应MongoDB的数据格式。
摘要由CSDN通过智能技术生成