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. python2 编码与解码

    #!coding: utf-8 s = "特斯拉" s_to_unicode = s.decode("utf-8") unicode_to_gbk = s_to ...

  2. Spark On Yarn报警告信息 WARN yarn.Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.

    1 贴出完整日志信息 // :: INFO client.RMProxy: Connecting to ResourceManager at hdp1/ // :: INFO yarn.Client: ...

  3. Java之@SuppressWarnings

    用了这个,MyEclipse里就不会报那些警告了,看起来漂亮多了 常用的:@SuppressWarnings("unchecked"),泛型@SuppressWarnings(&q ...

  4. 织梦自定义表单ajax提交范例

    function add_ajaxmessage(){ var dh = document.getElementById("tel"); //表单验证 if($("#te ...

  5. svn 的truck、tag、 merge

    参考文章 :    https://blog.csdn.net/keda8997110/article/details/21813035

  6. 《SSH网上商城》-视频目录--代码可以跑起来

    本课程是2015年2月份的,就是14年底的. 课程第一天的代码-添加 jsp-api.jar   servlet-api.jar就可以跑起来,环境 JDK1.7 和tomcat8, SSH网上商城\S ...

  7. css3基础一

    1,css简介 CSS 用于控制网页的样式和布局.样式定义如何显示html元素,样式通常保存在外部的 .css 文件中.通过仅仅编辑一个简单的 CSS 文档,外部样式表使你有能力同时改变站点中所有页面 ...

  8. 基于keepalived搭建MySQL热机集群

    背景 MySQL的高可用方案一般有如下几种: keepalived+双主,MHA,MMM,Heartbeat+DRBD,PXC,Galera Cluster 比较常用的是keepalived+双主,M ...

  9. golang printf中的%c,%d,%u.都分别代表输出的是什么类型的?

    %表示格式化字符串输出 目前printf支持以下格式的输出,例如: printf("%c",a):输出单个字符. printf("%d",a):输出十进制整数. ...

  10. PyQt4 / PyQt5

    Python事多,做个笔记,区分. PyQt5 Reference Guide http://pyqt.sourceforge.net/Docs/PyQt5/index.html Qt4 signal ...