写了一个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 Boot中的Mongodb多数据源扩展

    在日常工作中,我们通过Spring Data Mongodb来操作Mongodb数据库,在Spring Boot中只需要引入spring-boot-starter-data-mongodb即可. 然后 ...

  2. C# .NET Core 3.1中使用 MongoDB.Driver 更新嵌套数组元素和关联的一些坑

    C# .NET Core 3.1中使用 MongoDB.Driver 更新数组元素和关联的一些坑 前言: 由于工作的原因,使用的数据库由原来的 关系型数据库 MySQL.SQL Server 变成了 ...

  3. 随机记录工作中常见的sql用法错误(一)

    没事开始写博客,留下以前工作中常用的笔记,内容不全或者需要补充的可以留言,我只写我常用的. 网上很多类似动软生成器的小工具,这类工具虽然在表关系复杂的时候没什么软用,但是在一些简单的表结构关系还是很方 ...

  4. 工作中常用的js、jquery自定义扩展函数代码片段

    仅记录一些我工作中常用的自定义js函数. 1.获取URL请求参数 //根据URL获取Id function GetQueryString(name) { var reg = new RegExp(&q ...

  5. 工作中那些提高你效率的神器(第二篇)_Listary

    引言 无论是工作还是科研,我们都希望工作既快又好,然而大多数时候却迷失在繁杂的重复劳动中,久久无法摆脱繁杂的事情. 你是不是曾有这样一种想法:如果我有哆啦A梦的口袋,只要拿出神奇道具就可解当下棘手的问 ...

  6. 工作中那些提高你效率的神器(第一篇)_Everything

    引言 无论是工作还是科研,我们都希望工作既快又好,然而大多数时候却迷失在繁杂的重复劳动中,久久无法摆脱繁杂的事情. 你是不是曾有这样一种想法:如果我有哆啦A梦的口袋,只要拿出神奇道具就可解当下棘手的问 ...

  7. Atitit 软件开发中 瓦哈比派的核心含义以及修行方法以及对我们生活与工作中的指导意义

    Atitit 软件开发中 瓦哈比派的核心含义以及修行方法以及对我们生活与工作中的指导意义 首先我们指明,任何一种行动以及教派修行方法都有他的多元化,只看到某一方面,就不能很好的评估利弊,适不适合自己使 ...

  8. C# 工作中遇到的几个问题

    C#  工作中遇到的几个问题 1.将VS2010中的代码编辑器的默认字体“新宋体”改为“微软雅黑”后,代码的注释,很难对齐,特别是用SandCastle Help File Builder生成帮助文档 ...

  9. [工作中的设计模式]解释器模式模式Interpreter

    一.模式解析 解释器模式是类的行为模式.给定一个语言之后,解释器模式可以定义出其文法的一种表示,并同时提供一个解释器.客户端可以使用这个解释器来解释这个语言中的句子. 以上是解释器模式的类图,事实上我 ...

随机推荐

  1. golang开发:http请求redirect的问题

    这两天在开发项目的时候遇到了一个问题,请求了一个URL,它会302到另一个地址,本意上只是想检查这个URL是否会做3XX的redirect跳转,结果每次reqeust都会返回最后一跳的结果.后来就看了 ...

  2. D. Regular Bridge 解析(思維、圖論)

    Codeforce 550 D. Regular Bridge 解析(思維.圖論) 今天我們來看看CF550D 題目連結 題目 給你一個\(k\le100\),請構造出一個至少有一個Bridge的,每 ...

  3. Educational Codeforces Round 97 (Rated for Div. 2)

    补了一场Edu round. A : Marketing Scheme 水题 #include <cstdio> #include <algorithm> typedef lo ...

  4. 配置kuernetes集群pod拉取私有镜像仓库中的镜像

    目录 1 背景说明 2 实现方法 3 具体实现 配置镜像仓库项目为公开类型(任何人可以访问) 配置docker-registry类型的secret(pod使用secret获取镜像认证) 通过账户名密码 ...

  5. vue封装tab切换

    vue封装tab切换 预览: 第一种 通过父传子标题,子传父事件 子组件 <template> <div class='app'> <div class="ta ...

  6. Win10 Terminal + WSL 2 安装配置指南,精致开发体验

    自从 Windows Terminal 正式发布后就再没有用过 Windows 系统自带的终端了.主要是 Terminal 简洁且灵活,更重要的是支持特殊字体,通过一些简单的配置可以使得终端看起来更舒 ...

  7. insert into select 和select into from 备份表

    一 insert into select要求表必须存在 INSERTINTO order_record SELECT * FROM order_today FORCEINDEX (idx_pay_su ...

  8. 想springboot启动完成后执行某个方法

    如题,很多时候,我们都需要在springboot项目启动后初始化化一些自己的数据 原文地址:https://www.jianshu.com/p/f80f833ab8f6 实现方法有2个. 一.Appl ...

  9. zookeeper单机/集群安装和使用

    简书原文地址:https://www.jianshu.com/p/88194fde9a07 或者关注我的公众号"进阶者euj" 前提是本机有jdk 一.单机安装 1.去官网下载zo ...

  10. GitHub 上适合新手的开源项目(Python 篇)

    作者:HelloGitHub-卤蛋 随着 Python 语言的流行,越来越多的人加入到了 Python 的大家庭中.为什么这么多人学 Python ?我要喊出那句话了:"人生苦短,我用 Py ...