写了一个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'] )
)
);
}
}

最新文章

  1. [算法]——快速排序(Quick Sort)
  2. [CareerCup] 9.7 Paint Fill 填充
  3. [datatable]C# DataTable 如何排序
  4. Gym 100531H Problem H. Hiking in the Hills 二分
  5. VS2013 MVC Web项目使用内置的IISExpress支持局域网内部机器(手机、PC)访问、调试
  6. [置顶] hdu4747 Mex 线段树
  7. QT 下把编辑框内的中文字符转换为 char*
  8. 网页制作之html基础学习1-简介
  9. 最牛B的编程套路
  10. 制作、烧写根文件系统,使用NFS,编译使用驱动程序
  11. json中关于jo.[]中字符串一致的问题
  12. 用户关注微信公众号后,获取该用户的openID存数据库失败
  13. 设计模式的征途—9.组合(Composite)模式
  14. (2018干货系列五)最新UI设计学习路线整合
  15. LIRe提供的图像检索算法的速度
  16. luogu P5322 [BJOI2019]排兵布阵
  17. 在干净的ubuntu 14.10上编译Qemu2.2.0的过程
  18. python --- 18 类与类之间的关系, 特殊成员
  19. Selenium查询10010账户余额——python篇
  20. bet阶段验收互评

热门文章

  1. gethub网址链接
  2. uart与usart区别
  3. Python的Opencv库怎么装
  4. uniapp微信授权操作后事件不触发
  5. 一个名为不安全的类Unsafe
  6. CI框架导入 excel
  7. leetcode73:minmum-window-substring
  8. 完美实现CSS垂直居中的11种方法
  9. 一次webapi Post请求失败记录
  10. 解决git push出现error: failed to push some refs to 错误