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. 使用Python的turtle库画圣诞树

    代码如下: from turtle import * import random import time n = 80.0 speed("fastest") screensize( ...

  2. spring cloud(学习笔记)微服务启动错误(1)

    今天下午在启动spring cloud微服务的时候,报了这个错误: Error starting ApplicationContext. To display the auto-configurati ...

  3. MacOS下IntelliJ IDEA关联JDK1.8源码

    1 打开jdk设置,找到具体添加的地方 2 找到自己jdk的源码位置替换掉 3 如果没有源码或者源码没有下载解压,自己下载解压,Mac下安装的自带src.zip和javax-src.zip解压好后,再 ...

  4. actionsheet(操作表)

    推荐使用锚点方式显示.隐藏actionsheet: 若要使用js代码动态显示.隐藏actionsheet,同样在popover插件的构造方法中传入"toggle"参数即可 //传入 ...

  5. JQuery常见事件

    ##### 事件 onclick 单机事件 ondblclick 双击事件 onmouseover 鼠标穿过 (子盒子独立) onmouseout 鼠标出去 onmouseenter 鼠标进入 (子盒 ...

  6. 剑指Offer-滑动窗口的最大值

    题目描述 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值.例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6 ...

  7. day 8 - 1 文件操作

    文件操作 注意: 1. r+ 最为常用 2.encoding 的编码格式一定要与文件编码格式一致 读取 r  rb #在本地创建 txt 格式的文件默认使用 gbk 格式 f = open('e:/p ...

  8. Maven项目配置logback

    首先,在pom.xml中加入maven依赖 <!-- log start --> <dependency> <groupId>org.slf4j</group ...

  9. .Net Core 配置文件appsettings

    1.配置文件为appsettings 在appsettings添加ConnectionStrings: { "Logging": { "IncludeScopes&quo ...

  10. 使用AOP AspectJ 定义@Before,@After ,@Aroud后 执行两次

    背景 转眼之间,发现博客已经将近半年没更新了,甚是惭愧.话不多说,正如标题所言,最近在使用AspectJ的时候,发现拦截器(AOP切面)执行了两次了.我们知道,AspectJ是AOP的一种解决方案,本 ...