mongodb的基类

  1 <?php
  2
  3 namespace BI\Service\MongoDB;
  4
  5 use MongoDB\Driver\BulkWrite;
  6 use MongoDB\Driver\Exception\Exception;
  7 use MongoDB\Driver\Manager;
  8 use MongoDB\Driver\Query;
  9 use MongoDB\Driver\WriteConcern;
 10 use MongoDB\Driver\WriteResult;
 11 use MongoException;
 12
 13 class MongoDBManager
 14 {
 15     private $mongoManager;
 16     private $db;
 17
 18     function __construct($mongoDBConfig)
 19     {
 20         $connectString = 'mongodb://';
 21         if($mongoDBConfig['user'] && $mongoDBConfig['pass'])
 22             $connectString .= $mongoDBConfig['user'] . ':' . $mongoDBConfig['pass'] . '@';
 23         $connectString .= $mongoDBConfig['host'] . ':' . $mongoDBConfig['port'] . '/' . $mongoDBConfig['db'];
 24         $this->mongoManager = new Manager($connectString);
 25         $this->db = $mongoDBConfig['db'];
 26     }
 27
 28
 29     /**
 30      * @param string $collection
 31      * @param array $filter
 32      * @param array $options
 33      * @return array
 34      */
 35     public function executeQuery($collection, $filter = array(), $options = array()){
 36         $query = new Query($filter, $options);
 37         return $this->mongoManager->executeQuery($this->db . '.' . $collection, $query)->toArray();
 38     }
 39
 40     /**
 41      * @param string $collection
 42      * @param BulkWrite $bulkWrite
 43      * @return WriteResult
 44      */
 45     public function executeBulkWrite($collection, $bulkWrite){
 46         return $this->mongoManager->executeBulkWrite($this->db . '.' . $collection, $bulkWrite);
 47     }
 48
 49     /**
 50      * @param $doc
 51      * @param string $collection
 52      * @param bool $fetched
 53      * @return WriteResult
 54      */
 55     public function insertData($doc, $collection, $fetched = FALSE) {
 56         // do checking
 57         if (empty($doc) || $collection === NULL) {
 58             return false;
 59         }
 60
 61         // save data information
 62         try {
 63             //$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
 64
 65             $bulk = new BulkWrite();
 66             $insertedId = $bulk->insert($doc);
 67             $this->mongoManager->executeBulkWrite($this->db . '.' . $collection, $bulk);
 68
 69             //throw new MongoException('insert data failed');
 70
 71             if ($fetched) { return $insertedId; }
 72         }
 73         catch (Exception $e) {
 74             $this->throwError($e->getMessage());
 75         }
 76     }
 77
 78     /**
 79      * Update records
 80      * @param $collection
 81      * @param $filter
 82      * @param $updated
 83      * @param $options
 84      * @return WriteResult
 85      */
 86     public function updateData($collection, $filter, $updated, $options = array()) {
 87         // do checking
 88         if ($collection === NULL || empty($updated) || empty($filter)) {
 89             $this->throwError('Updated data can not be empty!');
 90         }
 91
 92         // do updating
 93         $timeout = 3000;
 94         $wc = new WriteConcern(WriteConcern::MAJORITY, $timeout);
 95         $bulk = new BulkWrite();
 96         $bulk->update($filter, $updated, $options);
 97         try {
 98             // execute
 99             return $this->mongoManager->executeBulkWrite("{$this->db}.$collection", $bulk, $wc);
100
101             // throw new MongoException('find record failed');
102         }
103         catch (\MongoException $e) {
104             $this->throwError($e->getMessage());
105         }
106     }
107
108     /**
109      * Delete record
110      * @param $collection
111      * @param $filter
112      * @param $options
113      * @return number of rows affected
114      */
115     public function deleteData($collection, $filter, $options=array()) {
116         // do checking
117         if ($collection === NULL) {
118             $this->throwError('Inserted data can not be empty!');
119         }
120
121         if (!is_array($filter)) {
122             $this->throwError('$filter format is invaild.');
123         }
124
125         try {
126             // execute
127             $bulk = new BulkWrite();
128             $bulk->delete($filter, $options);
129             $WriteResult = $this->mongoManager->executeBulkWrite("{$this->db}.$collection", $bulk);
130             return $WriteResult->getDeletedCount();
131
132             // throw new MongoException('delete record failed');
133         }
134         catch (MongoException $e) {
135             $this->throwError($e->getMessage());
136         }
137     }
138
139     /**
140      * throw error message
141      * @param string $errorInfo error message
142      */
143     private function throwError($errorInfo='') {
144         echo "<h3>Error:$errorInfo</h3>";
145     }
146 }
 

增删改查

class AlarmController
{
    CONST TIP = 'tip';//我习惯,mongodb里面的key写成常量
    public function checkTipAlarm()
    {
        $mongo = new MongoDBManager()

        //查询
        $result = $mongo->executeQuery(
            self::TIP,
            array(
                '_id' => new ObjectID( $this->request['rid'] )
            )
        );

        //新增
        $document = array(
            "msg" => $this->request['msg'],
            "owner" => $this->uuid,
            "to" => $this->request['to'],
            'type' => $this->request['type'],
            'flag' => self::FLAG_UNREAD,
            "inserted" => $function->millStampTime(),
            "status" => 1,
        );
        $result = $mongo->insertData($document, self::TIP, true);

        //更新
        $result = $mongo->updateData(
            self::TIP,
            array(
                '_id' => new ObjectID( $this->request['rid'] )
            ),
            array('$set' => array('status' => 0))
        );

        //删除
        $result = $mongo->deleteData(
            self::TIP,
            array(
                '_id' => new ObjectID( $this->request['rid'] )
            )
        );
    }
}

mongodb基类封装实例的更多相关文章

  1. 四、spring集成ibatis进行项目中dao层基类封装

    Apache iBatis(现已迁至Google Code下发展,更名为MyBatis)是当前IT项目中使用很广泛的一个半自动ORM框架,区别于Hibernate之类的全自动框架,iBatis对数据库 ...

  2. salesforce 零基础学习(四十八)自定义列表分页之Pagination基类封装 ※※※

    我们知道,salesforce中系统标准列表页面提供了相应的分页功能,如果要使用其分页功能,可以访问http://www.cnblogs.com/zero-zyq/p/5343287.html查看相关 ...

  3. Android 开发技巧 - Android 6.0 以上权限大坑和权限检查基类封装

    简单介绍 关于运行时权限的说法,早在Google发布android 6.0的时候,大家也听得蛮多的.从用户的角度来讲,用户是受益方,更好的保护用户的意思,而对于开发者来说,无疑增加了工作量. 对于6. ...

  4. thinkphp5底层基类封装、内部类函数

    记录下thinkphp5自定义底层基类.内部类函数使用笔记 大部分笔记来自tp手册. 底层常用代码的封装 在控制器中基类的起着至关重要的作用,整个项目的代码安全,复杂程度,易读性都要看你项目的基类架构 ...

  5. python 打飞机项目 ( 基类封装 )

    项目代码 | plane # -*- coding:utf-8 -*- import pygame, time from Plane import Plane from HeroPlane impor ...

  6. C#中将xml文件反序列化为实例时采用基类还是派生类的问题

    基类: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ...

  7. python(五):面向对象--类和实例

    一.类的基本概念 类是用来创建数据结构和新类型对象的主要机制.一个类定义了一系列与其实例对象密切关联的属性.典型的属性包括变量(也被称为 类变量)和函数(又被称为方法). 1.class上下文 cla ...

  8. JAVA单例MongoDB工具类

    我经常对MongoDB进行一些基础操作,将这些常用操作合并到一个工具类中,方便自己开发使用. 没用Spring Data.Morphia等框架是为了减少学习.维护成本,另外自己直接JDBC方式的话可以 ...

  9. C#在派生类中调用基类成员

    一.在派生类中调用基类成员 在C#的派生类中,我们可以使用base关键字调用基类中的公有或者受保护成员.这些成员只能是构造函数.实例方法或者实例属性. base关键字调用基类成员的语法格式如下: ba ...

随机推荐

  1. luogu P4491 [HAOI2018]染色

    传送门 这一类题都要考虑推式子 首先推出题目要求的式子,枚举正好有\(s\)个颜色的种类(范围\([0,p=min(\lfloor\frac{n}{s}\rfloor,m)]\)),然后对于后面的颜色 ...

  2. Flume思维导图

  3. 通过命令窗口控制mysql服务的启动与停止

    mysql服务的启动: 以管理员的身份运行cmd命令窗口,输入命名 net start mysql 如果不是以管理员的身份运行cmd,会提示如下错误 mysql服务的停止: 以管理员的身份运行cmd命 ...

  4. js开发模式

    js中的开发模式进化史: js中有最初的只能由基本数据类型描述——>单例模式-->工厂模式-->构造函数模式-->原型模式-->各个模式相结合的混合模式,下面我会给大家逐 ...

  5. 模拟post表单提交参数

    Content-Type: application/x-www-form-urlencoded;charset=utf-8

  6. 发布逸出 java this 逸出【转】

    转自:http://blog.csdn.net/joker_zhou/article/details/7322801 (1)发布:发布是指将一个对象,使其引用储存到一个其他代码可以访问到的地方,在一个 ...

  7. 【转】python 面向对象(进阶篇)

    [转]python 面向对象(进阶篇) 上一篇<Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 ...

  8. css利用padding百分比实现图片自适应高度

    应用场景 宽高比率,实现图片自适应高度,防止图片加载过程高度为0,加载完图片高度撑起,它下面的div抖动问题 重点:CSS百分比padding都是相对宽度计算的 <div class=" ...

  9. python3+selenium入门06-浏览器操作

    WebDriver主要提供元素操作的方法,但也提供了一些关于浏览器操作的方法,比如设置浏览器大小,浏览器前进,后退,刷新等 设置浏览器大小 有时候需要设置浏览器大小,比如访问收集网页,设置浏览器大小跟 ...

  10. boost::asio实现一个echo服务器

    以前使用ACE实现Server框架,但是觉得太笨重,决定采用boost.asio来写服务器程序: 1.服务器构建在linux上面:当然也可以在windows下运行 2.io部分采用非阻塞模式.业务逻辑 ...