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. 第20月第29天 cocoa抽象工厂 cocoapods组件化 cocoapods升级

    1. 在 Cocoa Touch 框架中,类簇是抽象工厂模式在 iOS 下的一种实现,以 NSArray 举例,将原有的 alloc+init 拆开写: id obj1 = [NSArray allo ...

  2. linux全部替换命令学习

    :%s/准备替换内容/新内容/g 可以使用 # 作为分隔符,此时中间出现的 / 不会作为分隔符 :%s#vivian/#sky/#g 替换 vivian/ 为 sky/ :%s+/oradata/ap ...

  3. 剑指Offer-表示数值的字符串

    题目描述 请实现一个函数用来判断字符串是否表示数值(包括整数和小数).例如,字符串"+100","5e2","-123","3.1 ...

  4. python 数据分析3

    本节概要 pandas简介 安装 pip install pandas pandas的2个主要数据结构:DataFrame 和 Series Series series是一种类似于一维数组的对象,它由 ...

  5. html转成pdf,下载(html2canvas 和 jsPDF)

    参考链接:https://github.com/linwalker/render-html-to-pdf

  6. linux上安装Docker(非常简单的安装方法)

    Docker的三大核心概念:镜像.容器.仓库 镜像:类似虚拟机的镜像.用俗话说就是安装文件. 容器:类似一个轻量级的沙箱,容器是从镜像创建应用运行实例, 可以将其启动.开始.停止.删除.而这些容器都是 ...

  7. Kivy折腾笔记

    最近想用Python开发APP,选择kivy,记录过程 首先是源码安装,各种蛋疼的报错放弃了.cython高版本有问题. python3 -m pip install cython==0.23 pyt ...

  8. QR 编码原理(三)

    一.日本汉字(KANJI)是两个字节表示的字符码,编码的方式是将其转换为13字节的二进制码制. 转换步骤为: 1.对于JIS值为8140(hex) 到9FFC(hex)之间字符: a)将待转换的JIS ...

  9. launch 文件的写法

    1. launch文件的写法 ❀标签          ☺<node> 启动一个节点          ☺ <param> 设置参数服务器的参数          ☺ < ...

  10. 原生js的开发笔记

    1.基本的dom操作 var a=document.getElementById('ma1').innerHTML;/获取html代码 alert(document.getElementById('m ...