php操作MongoDB类实例


Posted in PHP onJune 17, 2015

本文实例讲述了php操作MongoDB类的方法。分享给大家供大家参考。具体如下:

1. MyMongo.php文件:

<?php
/**
 * 仿写CI的MongoDB
 * @author sparkHuang 2011-11-03
 *
 */
class MyMongo {
  private $mongo_config = "mongo_config.php";
  private $connection;
  private $db;
  private $mongo_connect_string;
  private $host;
  private $port;
  private $user;
  private $pass;
  private $dbname;
  private $persist;
  private $persist_key;
  private $selects = array();
  private $wheres = array();
  private $sorts = array();
  private $limit = 999999;
  private $offset = 0;
  public function __construct() {
    if ( ! class_exists('Mongo')) {
      $this->log_error("The MongoDB PECL extentiosn has not been installed or enabled.");
      exit;
    }
    
    $this->connection_string();
    $this->connect();
  }
  /**
   * 更改数据库
   *
   */
  public function switch_db($database = '') {
    if (empty($database)) {
      $this->log_error("To switch MongoDB databases, a new database name must be specified");
      exit;
    }
    $this->dbname = $database;
    try {
      $this->db = $this->connection->{$this->dbname};
      return true;
    } catch(Exception $e) {
      $this->log_error("Unable to switch Mongo Databases: {$e->getMessage()}");
      exit;
    }
  }
  /**
   * 设置select字段
   *
   */
  public function select($includs = array(), $excludes = array()) {
    if ( ! is_array($includs)) {
      $includs = (array)$includs;
    }
    
    if ( ! is_array($excludes)) {
      $excludes = (array)$excludes;
    }
    
    if ( ! empty($includs)) {
      foreach ($includs as $col) {
        $this->selects[$col] = 1;
      }
    } else {
      foreach ($excludes as $col) {
        $this->selects[$col] = 0;
      }
    }
    
    return($this);
  }
  /**
   * where条件查询判断
   *
   * @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar');
   *
   */
  public function where($wheres = array()) {
    if ( ! is_array($wheres)) {
      $wheres = (array)$wheres;
    }
    
    if ( ! empty($wheres)) {
      foreach($wheres as $wh => $val) {
        $this->wheres[$wh] = $val;
      }
    }
    
    return($this);
  }
  /**
   * where ... in .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_in('foo', array('bar', 'zoo'))->get('foobar');
   *
   */
  public function where_in($field = '', $in = array()) {
    $this->where_init($field);
    $this->wheres[$field]['$in'] = $in;
    return($this);
  }
  /**
   * where ... not in .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo'))->get('foobar');
   *
   */
  public function where_not_in($field = '', $in = array()) {
    $this->where_init($field);
    $this->wheres[$field]['$nin'] = $in;
    return($this);
  }
  /**
   * where ... $field > $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_gt('foo', 20)->get('foobar');
   *
   */
  public function where_gt($field = '', $x) {
    $this->where_init($field);
    $this->wheres[$field]['$gt'] = $x;
    return($this);
  }
  /**
   * where ... $field >= $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_gte('foo', 20)->get('foobar');
   *
   */
  public function where_gte($field = '', $x) {
    $this->where_init($field);
    $this->wheres[$field]['$gte'] = $x;
    return($this);
  }
  /**
   * where ... $field < $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_lt('foo', 20)->get('foobar');
   *
   */
  public function where_lt($field = '', $x) {
    $this->where_init($field);
    $this->wheres[$field]['$lt'] = $x;
    return($this);
  }
  /**
   * where ... $field <= $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_lte('foo', 20)->get('foobar');
   *
   */
  public function where_lte($field = '', $x) {
    $this->where_init($field);
    $this->wheres[$field]['$lte'] = $x;
    return($this);
  }
  /**
   * where ... $field >= $x AND $field <= $y .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_between('foo', 20, 30)->get('foobar');
   *
   */
  public function where_between($field = '', $x, $y) {
    $this->where_init($field);
    $this->wheres[$field]['$gte'] = $x;
    $this->wheres[$field]['$lte'] = $y;
    return($this);
  }
  /**
   * where ... $field > $x AND $field < $y .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_between_ne('foo', 20, 30)->get('foobar');
   *
   */
  public function where_between_ne($field = '', $x, $y) {
    $this->where_init($field);
    $this->wheres[$field]['$gt'] = $x;
    $this->wheres[$field]['$lt'] = $y;
    return($this);
  }
  /**
   * where ... $field <> $x .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_ne('foo', 20)->get('foobar');
   *
   */
  public function where_ne($field = '', $x) {
    $this->where_init($field);
    $this->wheres[$field]['$ne'] = $x;
    return($this);
  }
  /**
   * where ... or .. 条件查询判断
   *
   * @usage = $this->mongo_db->where_or('foo', array('foo', 'bar'))->get('foobar');
   *
   */
  public function where_or($field = '', $values) {
    $this->where_init($field);
    $this->wheres[$field]['$or'] = $values;
    return($this);
  }
  /**
   *  where ... and .. 条件查询判断
   *  
   *  @usage = $this->mongo_db->where_and( array ( 'foo' => 1, 'b' => 'someexample' );
   */
   public function where_and( $elements_values = array() ) {
     foreach ( $elements_values as $element => $val ) {
       $this->wheres[$element] = $val;
     }
     return($this);
   }
  /**
   *  where $field % $num = $result
   *
   *  @usage = $this->mongo_db->where_mod( 'foo', 10, 1 );
   */   
   public function where_mod( $field, $num, $result ) {
     $this->where_init($field);
     $this->wheres[$field]['$mod'] = array($num, $result);
     return($this);
   }
  /**
   * where size
   *
   *  Get the documents where the size of a field is in a given $size int
   *
   *  @usage : $this->mongo_db->where_size('foo', 1)->get('foobar');
   */
  public function where_size($field = "", $size = "") {
    $this->where_init($field);
    $this->wheres[$field]['$size'] = $size;
    return ($this);
  }
  /**
   * like条件查询(PHP中定义MongoRegex类实现)
   *
   * @usage : $this->mongo_db->like('foo', 'bar', 'im', false, false)->get();
   */
  public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = true, $enable_end_wildcard = true) {
    $field = (string)$field;
    $this->where_init($field);
    $value = (string)$value;
    $value = quotmeta($value);
    
    if (true !== $enable_start_wildcard) {
      $value = "^".$value;
    }
    
    if (true !== $enable_end_wildcard) {
      $value .= "$";
    }
    
    $regex = "/$value/$flags";
    $this->wheres[$field] = new MongoRegex($regex);
    return($this);
  }
  /**
   * order排序( 1 => ASC, -1 => DESC)
   *
   * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->order_by(array("age" => 1));
   */
  public function order_by($fields = array()) {
    foreach($fields as $col => $val) {
      if ($val == -1 || $val == false || strtolower($val) == "desc") {
        $this->sorts[$col] = -1;
      } else {
        $this->sorts[$col] = 1;
      }
    }
    return($this);
  }
  /**
   * limit
   *
   * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->limit(10);
   */
  public function limit($x = 999999) {
    if ($x !== NULL && is_numeric($x) && $x >= 1) {
      $this->limit = (int)$x;
    }
    return($this);
  }
  /**
   * offset
   *
   * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->offset(10);
   */
  public function offset($x = 0) {
     if($x !== NULL && is_numeric($x) && $x >= 1) {
       $this->offset = (int) $x;
     }
     return($this);
  }
  /**
   * get_where
   * 
   * @usage: $this->mongo_db->get_where('foo', array('bar' => 'something'));
   */
  public function get_where($collection = "", $where = array(), $limit = 999999) {
    return($this->where($where)->limit($limit)->get($collection));
  }
  /**
   * get
   *
   * @usage: $this->mongo_db->where(array('name' => 'tom'))->get('foo');
   */
  public function get($collection) {
    if (empty($collection)) {
      $this->log_error("In order to retreive documents from MongoDB, a collection name must be passed");
      exit;
    }
    $results = array();
    $results = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int)$this->limit)->skip((int)$this->offset)->sort($this->sorts);
    $returns = array();
    foreach($results as $result) {
      $returns[] = $result;
    }
    $this->clear();
    return($returns);
  }
  /**
   * count
   *
   * @usage: $this->db->get_where('foo', array('name' => 'tom'))->count('foo'); 
   */
  public function count($collection) {
    if (empty($collection)) {
      $this->log_error("In order to retreive documents from MongoDB, a collection name must be passed");
      exit;
    }
    $count = $this->db->{$collection}->find($this->wheres)->limit((int)$this->limit)->skip((int)$this->offset)->count();
    $this->clear();
    return($count);
  }
  /**
   * insert
   *
   * @usage: $this->mongo_db->insert('foo', array('name' => 'tom'));
   */
  public function insert($collection = "", $data = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection selected to delete from");
      exit;
    }
    if (count($data) == 0 || ! is_array($data)) {
      $this->log_error("Nothing to insert into Mongo collection or insert is not an array");
      exit;
    }
    try {
      $this->db->{$collection}->insert($data, array('fsync' => true));
      if (isset($data['_id'])) {
        return($data['_id']);
      } else {
        return(false);
      }
    } catch(MongoCursorException $e) {
      $this->log_error("Insert of data into MongoDB failed: {$e->getMessage()}");
      exit;
    }
  }
  /**
   * update : 利用MongoDB的 $set 实现
   *
   * @usage : $this->mongo_db->where(array('name' => 'tom'))->update('foo', array('age' => 24))
   */
  public function update($collection = "", $data = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection selected to delete from");
      exit;
    }
    if (count($data) == 0 || ! is_array($data)) {
      $this->log_error("Nothing to update in Mongo collection or update is not an array");
      exit;
    }
    try {
      $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => true, 'multiple' => false)); //注意: multiple为false
      return(true);
    } catch(MongoCursorException $e) {
      $this->log_error("Update of data into MongoDB failed: {$e->getMessage()}");
      exit;
    }
  }
  /**
   * update_all : 利用MongoDB的 $set 实现
   *
   * @usage : $this->mongo_db->where(array('name' => 'tom'))->update_all('foo', array('age' => 24));
   */
  public function update_all($collection = "", $data = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection selected to delete from");
      exit;
    }
    if (count($data) == 0 || ! is_array($data)) {
      $this->log_error("Nothing to update in Mongo collection or update is not an array");
      exit;
    }
    try {
      $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => true, 'multiple' => true)); //注意: multiple为true
      return(true);
    } catch(MongoCursorException $e) {
      $this->log_error("Update of data into MongoDB failed: {$e->getMessage()}");
      exit;
    }
  }
  /**
   * delete 
   *
   * @usage : $this->mongo_db->where(array('name' => 'tom'))->delete('foo');
   */
  public function delete($collection = "") {
    if (empty($collection)) {
      $this->log_error("No Mongo collection selected to delete from");
      exit;
    }
    try {
      $this->db->{$collection}->remove($this->wheres, array('fsync' => true, 'justOne' => true)); //注意justOne为true;
    } catch(MongoCursorException $e) {
      $this->log_error("Delete of data into MongoDB failed: {$e->getMessage()}");
      exit;
    }
  }  
  /**
   * delete_all
   *
   * @usage : $this->mongo_db->where(array('name' => 'tom'))->delete_all('foo');
   */
  public function delete_all($collection = "") {
    if (empty($collection)) {
      $this->log_error("No Mongo collection selected to delete from");
      exit;
    }
    try {
      $this->db->{$collection}->remove($this->wheres, array('fsync' => true, 'justOne' => false)); //注意justOne为false;
    } catch(MongoCursorException $e) {
      $this->log_error("Delete of data into MongoDB failed: {$e->getMessage()}");
      exit;
    }
  }
  /** 
   * add_index
   *
   * @usage : $this->mongo_db->add_index('foo', array('first_name' => 'ASC', 'last_name' => -1), array('unique' => true)));
   */
  public function add_index($collection, $keys = array(), $options = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection specified to add index to");
      exit;
    }
    if (empty($keys) || ! is_array($keys)) {
      $this->log_error("Index could not be created to MongoDB Collection because no keys were specified");
      exit;
    }
    foreach($keys as $col => $val) {
      if ($val == -1 || $val == false || strtolower($val) == 'desc') {
        $keys[$col] = -1;
      } else {
        $keys[$col] = 1;
      }
    }
    //在此没有对$options数组的有效性进行验证
    if (true == $this->db->{$collection}->ensureIndex($keys, $options)) {
      $this->clear();
      return($this);
    } else {
      $this->log_error("An error occured when trying to add an index to MongoDB Collection");
      exit;
    }
  }
  /**
   * remove_index
   *
   * @usage : $this->mongo_db->remove_index('foo', array('first_name' => 'ASC', 'last_name' => -1))
   */
  public function remove_index($collection = "", $keys = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection specified to add index to");
      exit;
    }
    if (empty($keys) || ! is_array($keys)) {
      $this->log_error("Index could not be created to MongoDB Collection because no keys were specified");
      exit;
    }
    if ($this->db->{$collection}->deleteIndex($keys)) {
      $this->clear();
      return($this);
    } else {
      $this->log_error("An error occured when trying to add an index to MongoDB Collection");
      exit;
    }
  }
  /**
   * remove_all_index
   *
   * @usage : $this->mongo_db->remove_all_index('foo', array('first_name' => 'ASC', 'last_name' => -1))
   */
  public function remove_all_index($collection = "", $keys = array()) {
    if (empty($collection)) {
      $this->log_error("No Mongo collection specified to add index to");
      exit;
    }
    if (empty($keys) || ! is_array($keys)) {
      $this->log_error("Index could not be created to MongoDB Collection because no keys were specified");
      exit;
    }
    if ($this->db->{$collection}->deleteIndexes($keys)) {
      $this->clear();
      return($this);
    } else {
      $this->log_error("An error occured when trying to add an index to MongoDB Collection");
      exit;
    }
  }
  /**
   * list_indexes
   *
   * @usage : $this->mongo_db->list_indexes('foo');
   */
  public function list_indexes($collection = "") {
    if (empty($collection)) {
      $this->log_error("No Mongo collection specified to add index to");
      exit;
    }
    return($this->db->{$collection}->getIndexInfo());
  }
  /**
   * drop_collection
   *
   * @usage : $this->mongo_db->drop_collection('foo');
   */
  public function drop_collection($collection = "") {
    if (empty($collection)) {
      $this->log_error("No Mongo collection specified to add index to");
      exit;
    }
    $this->db->{$collection}->drop();
    return(true);
  }
  /**
   * 生成连接MongoDB 参数字符串
   *
   */
  private function connection_string() {
    include_once($this->mongo_config);
    $this->host = trim($config['host']);
    $this->port = trim($config['port']);
    $this->user = trim($config['user']);
    $this->pass = trim($config['pass']);
    $this->dbname = trim($config['dbname']);
    $this->persist = trim($config['persist']);
    $this->persist_key = trim($config['persist_key']);
    $connection_string = "mongodb://";
    if (empty($this->host)) {
      $this->log_error("The Host must be set to connect to MongoDB");
      exit;
    }
    if (empty($this->dbname)) {
      $this->log_error("The Database must be set to connect to MongoDB");
      exit;
    }
    if ( ! empty($this->user) && ! empty($this->pass)) {
      $connection_string .= "{$this->user}:{$this->pass}@";
    }
    if ( isset($this->port) && ! empty($this->port)) {
      $connection_string .= "{$this->host}:{$this->port}";
    } else {
      $connection_string .= "{$this->host}";
    }
    $this->connection_string = trim($connection_string);
  }
  /**
   * 连接MongoDB 获取数据库操作句柄
   *
   */
  private function connect() {
    $options = array();
    if (true === $this->persist) {
      $options['persist'] = isset($this->persist_key) && ! empty($this->persist_key) ? $this->persist_key : "ci_mongo_persist";
    }
    try {
      $this->connection = new Mongo($this->connection_string, $options);
      $this->db = $this->connection->{$this->dbname};
      return ($this);
    } catch (MongoConnectionException $e) {
      $this->log_error("Unable to connect to MongoDB: {$e->getMessage()}");
    }
  }
  /**
   * 初始化清理部分成员变量
   * 
   */
  private function clear() {
    $this->selects = array();
    $this->wheres = array();
    $this->limit = NULL;
    $this->offset = NULL;
    $this->sorts = array();
  }
  /**
   * 依据字段名初始化处理$wheres数组
   *
   */
  private function where_init($param) {
    if ( ! isset($this->wheres[$param])) {
      $this->wheres[$param] = array();
    }
  }
  /**
   * 错误记录
   *
   */
  private function log_error($msg) {
    $msg = "[Date: ".date("Y-m-i H:i:s")."] ".$msg;
    @file_put_contents("./error.log", print_r($msg."\n", true), FILE_APPEND);
  }
}
/* End of MyMongo.php */

2. mongo_config.php配置文件:

<?php
$config["host"] = "localhost";
$config["user"] = "";
$config["pass"] = "";
$config["port"] = 27017;
$config["dbname"] = "test";
$config['persist'] = TRUE;
$config['persist_key'] = 'ci_mongo_persist';
/*End of mongo_config.php*/

3. MyMongoDemo.php文件:

<?php
include_once("MyMongo.php");
$conn = new MyMongo();
//删除所有记录
$conn->delete_all("blog");
//插入第一条记录
$value = array("name" => "小明", "age" => 25, "addr" => array("country" => "中国", "province" => "广西", "city" => "桂林"));
$conn->insert("blog", $value);
var_dump($conn->select(array("name", "age"))->get("blog"));
var_dump($conn->get("blog"));
/* End of MyMongoDemo.php */

希望本文所述对大家的php程序设计有所帮助。

PHP 相关文章推荐
WINDOWS 2000下使用ISAPI方式安装PHP
Sep 05 PHP
PHP foreach循环使用详解与实例代码
May 08 PHP
使用PHP导出Word文档的原理和实例
Oct 21 PHP
关于php内存不够用的快速解决方法
Oct 26 PHP
php中Y2K38的漏洞解决方法实例分析
Sep 22 PHP
PHP+jQuery 注册模块开发详解
Oct 14 PHP
Codeigniter购物车类不能添加中文的解决方法
Nov 29 PHP
PHP实现的oracle分页函数实例
Jan 25 PHP
PHP7下协程的实现方法详解
Dec 17 PHP
关于PHP虚拟主机概念及如何选择稳定的PHP虚拟主机
Nov 20 PHP
PHP安装BCMath扩展的方法
Feb 13 PHP
PHP的curl函数的用法总结
Feb 14 PHP
PHP实现的购物车类实例
Jun 17 #PHP
CodeIgniter实现从网站抓取图片并自动下载到文件夹里的方法
Jun 17 #PHP
PHP基于MySQL数据库实现对象持久层的方法
Jun 17 #PHP
php使用curl打开https网站的方法
Jun 17 #PHP
php使用CURL不依赖COOKIEJAR获取COOKIE的方法
Jun 17 #PHP
PHP封装的HttpClient类用法实例
Jun 17 #PHP
PHP处理postfix邮件内容的方法
Jun 16 #PHP
You might like
使用PHP获取当前url路径的函数以及服务器变量
2013/06/29 PHP
PHP类中的魔术方法(Magic Method)简明总结
2014/07/08 PHP
DOM基础及php读取xml内容操作的方法
2015/01/23 PHP
php+ajax实现带进度条的上传图片功能【附demo源码下载】
2016/09/14 PHP
PHP 极验验证码实例讲解
2016/09/29 PHP
利用php抓取蜘蛛爬虫痕迹的示例代码
2016/09/30 PHP
php 数组处理函数extract详解及实例代码
2016/11/23 PHP
Yii2.0使用阿里云OSS的SDK上传图片、下载、删除图片示例
2017/09/20 PHP
ExtJS 工具栏 分页事件参数
2010/03/05 Javascript
javascript 类型判断代码分析
2010/03/28 Javascript
jquery插件制作 图片走廊 gallery
2012/08/17 Javascript
JQuery控制div外点击隐藏而div内点击不会隐藏的方法
2015/01/13 Javascript
bootstrap实现弹窗和拖动效果
2016/01/03 Javascript
JavaScript常用函数工具集:lao-utils
2016/03/01 Javascript
JavaScript实现广告弹窗效果
2016/08/09 Javascript
JavaScript面向对象编写购物车功能
2016/08/19 Javascript
Bootstrap模态框禁用空白处点击关闭
2016/10/20 Javascript
JS正则RegExp.test()使用注意事项(不具有重复性)
2016/12/28 Javascript
Angular中使用better-scroll插件的方法
2018/03/27 Javascript
通过一次报错详细谈谈Point事件
2018/05/17 Javascript
vue mounted组件的使用
2018/06/18 Javascript
Vue验证码60秒倒计时功能简单实例代码
2018/06/22 Javascript
vue elementUI 表单校验功能之数组多层嵌套
2019/06/04 Javascript
Python数据分析库pandas基本操作方法
2018/04/08 Python
python获取指定日期范围内的每一天,每个月,每季度的方法
2019/08/08 Python
Python之Class&amp;Object用法详解
2019/12/25 Python
HTML5使用Audio标签实现歌词同步的效果
2016/03/17 HTML / CSS
美国在线鲜花速递:ProFlowers
2017/01/05 全球购物
Skyscanner澳大利亚:全球领先的旅游搜索网站
2018/03/24 全球购物
Gerry Weber德国官网:优质女性时装,德国最大的时装公司之一
2019/11/02 全球购物
Kiehl’s科颜氏西班牙官方网站:源自美国的植物护肤品牌
2020/02/22 全球购物
后勤管理员岗位职责
2014/08/27 职场文书
学校关爱留守儿童活动方案
2014/08/27 职场文书
2015年全国爱眼日活动小结
2015/02/27 职场文书
幼儿园中班教育随笔
2015/08/14 职场文书
使用qt quick-ListView仿微信好友列表和聊天列表的示例代码
2021/06/13 Python