MongoUtil.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <?php
  2. namespace loyalsoft;
  3. /*
  4. * File:MongoUtil.php
  5. * Function: MongoDB operation helper.
  6. * Author: gwang(wanggangzero@qq.com)
  7. * Version:
  8. * 1.0.0 Creat file. --gwang 2022.2.14
  9. */
  10. /**
  11. * MongoDB辅助类
  12. * Author: gwang(wanggangzero@qq.com)
  13. */
  14. class MongoUtil {
  15. /**
  16. * 负责与MongoDB连接, 管理
  17. * @var \MongoDB\Driver\Manager
  18. */
  19. private $mc;
  20. /**
  21. * 返回一个新的option构造器,请使用链式写法追加所有option, 最后用GetOption()获取最终的option数组
  22. * @author gwang <wanggangzero@qq.com>
  23. * @return \loyalsoft\MongoQueryOptionBuilder
  24. */
  25. public static function QueryOptionBuilder() {
  26. return new MongoQueryOptionBuilder();
  27. }
  28. /**
  29. *
  30. * @param type $connStr
  31. * @return \MongoDB\Driver\Manager|false
  32. */
  33. public function conn($connStr) {
  34. try {
  35. $this->mc = new \MongoDB\Driver\Manager($connStr);
  36. return $this->mc;
  37. } catch (\Exception $e) {
  38. Clog::err($e->getMessage());
  39. return false;
  40. }
  41. }
  42. /**
  43. * 查询
  44. * @author gwang<wanggangzero@qq.com>
  45. * @param string $collection 集合
  46. * @param array $filter 同过滤器语法
  47. * @param array $options 请利用QueryOptionBuilder()来辅助定制选项
  48. * @return \MongoDB\Driver\Cursor|false
  49. */
  50. public function find($collection, $filter = [], $options = []) {
  51. if (empty($this->mc)) {
  52. return false;
  53. }
  54. try {
  55. $query = new \MongoDB\Driver\Query($filter, $options);
  56. $cursor = $this->mc->executeQuery($collection, $query);
  57. return $cursor;
  58. } catch (\Exception $ex) {
  59. CLog::err($ex->getMessage());
  60. return false;
  61. }
  62. }
  63. /**
  64. * 插入1条数据
  65. * @param string $collection 表名(db.collection)
  66. * @param array $addArr 待插入的数据,要求是数组
  67. * @return boolean
  68. */
  69. public function insert($collection, $addArr) {
  70. if (empty($addArr) || !is_array($addArr)) {
  71. return false;
  72. }
  73. if (empty($this->mc)) {
  74. return false;
  75. }
  76. try {
  77. $bulk = new \MongoDB\Driver\BulkWrite();
  78. $bulk->insert($addArr);
  79. $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 6000);
  80. $result = $this->mc->executeBulkWrite($collection, $bulk, $writeConcern);
  81. if ($result->getInsertedCount()) {
  82. return true;
  83. }
  84. } catch (\Exception $e) {
  85. CLog::err($e->getMessage()); # 记录错误日志
  86. }
  87. return false;
  88. }
  89. /**
  90. * 删除
  91. * @param string $collection 表名
  92. * @param array $whereArr 筛选条件
  93. * @param bool $limit 是否仅删除第一条(默认false,删除所有匹配条目)
  94. * @return boolean
  95. */
  96. public function delete($collection, $whereArr, $limit = false) {
  97. if (empty($whereArr)) {
  98. return false;
  99. }
  100. $options = ['limit' => $limit];
  101. $conn = $this->mc;
  102. if (empty($conn)) {
  103. return false;
  104. }
  105. try {
  106. $bulk = new \MongoDB\Driver\BulkWrite();
  107. $bulk->delete($whereArr, $options);
  108. $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 30000);
  109. $result = $conn->executeBulkWrite($collection, $bulk, $writeConcern);
  110. return $result->getDeletedCount();
  111. } catch (\Exception $e) {
  112. CLog::err($e->getMessage()); # 记录错误日志
  113. }
  114. return false;
  115. }
  116. /**
  117. * 更新
  118. * @param string $collection
  119. * @param array $whereArr 条件
  120. * @param array $newPropertiesArr 可以是一个新文档, 也可以是一个opration数组(eg. $set表达式), 还可以是一组update 管道(批量参考https://docs.mongodb.com/manual/reference/command/update/#update-with-an-aggregation-pipeline)
  121. * @param bool $upsert 当符合条件的文档不存在时是否作为一条新的文档插入(当新数据为文档时生效,operation不可以)
  122. * @param bool $multi 是否一次更新多个文档的值(当新数据为operation表达式时可以,否则不可以) 默认false
  123. * @return boolean
  124. */
  125. public function update($collection, $whereArr, $newPropertiesArr, $upsert = true, $multi = false) {
  126. if (empty($whereArr) || empty($newPropertiesArr)) {
  127. return false;
  128. }
  129. $options = ['multi' => $multi, 'upsert' => $upsert];
  130. $conn = $this->mc;
  131. if (empty($conn)) {
  132. return false;
  133. }
  134. try {
  135. $bulk = new \MongoDB\Driver\BulkWrite();
  136. $bulk->update($whereArr, $newPropertiesArr, $options);
  137. $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 30000);
  138. $result = $conn->executeBulkWrite($collection, $bulk, $writeConcern);
  139. return $result->getUpsertedCount() + $result->getModifiedCount();
  140. } catch (\Exception $e) {
  141. CLog::err($e->getMessage()); # 记录错误日志
  142. }
  143. return false;
  144. }
  145. }
  146. /**
  147. * 查询选项构造器
  148. * @author gwang <wanggangzero@qq.com>
  149. */
  150. class MongoQueryOptionBuilder {
  151. /**
  152. * 内部对象
  153. */
  154. private $option = array();
  155. /**
  156. * 返回最终的 options
  157. * @return array
  158. */
  159. public function GetOption() {
  160. return $this->option;
  161. }
  162. /**
  163. * 参照MySQL的 explain
  164. * @param bool $yes
  165. * @return MongoQueryOptionBuilder
  166. */
  167. public function explain($yes = true) {
  168. $this->option[__FUNCTION__] = $yes;
  169. return $this;
  170. }
  171. /**
  172. * 限定返回值数量(0=无限制)
  173. * @param int $limit 默认 0
  174. * @return MongoQueryOptionBuilder
  175. */
  176. public function limit($limit = 0) {
  177. $this->option[__FUNCTION__] = $limit;
  178. return $this;
  179. }
  180. /**
  181. * 限定返回值跳过前n个文档(索引从0开始)
  182. * @param int $n 默认值0
  183. * @return MongoQueryOptionBuilder
  184. */
  185. public function skip($n = 0) {
  186. $this->option[__FUNCTION__] = $n;
  187. return $this;
  188. }
  189. /**
  190. * project
  191. * @param array $arr 假如MQL中为{$project:{key:1,name:"$value.baseInfo.name"}}
  192. * 则此处['key'=>1,'name'=>'$value.baseInfo.name'] 注意如果包含$符使用单引号
  193. * @return MongoQueryOptionBuilder
  194. */
  195. public function projection($arr = array()) {
  196. $this->option[__FUNCTION__] = $arr;
  197. return $this;
  198. }
  199. /**
  200. * 必须与 tailable awaitData 结合使用.
  201. * 设定正整数值可以让服务器阻塞对应的毫秒数(没有数据的前提下,有数据自然直接返回)
  202. * @param int $n
  203. * @return MongoQueryOptionBuilder
  204. */
  205. public function maxAwaitTimeMS($n = 0) {
  206. $this->option[__FUNCTION__] = $n;
  207. return $this;
  208. }
  209. /**
  210. * 只返回索引
  211. * @param bool $yes 默认值false, 当设为true时,你应该了解会返回什么.
  212. * @return $this
  213. */
  214. public function returnKey($yes = false) {
  215. $this->option[__FUNCTION__] = $yes;
  216. return $this;
  217. }
  218. /**
  219. * The sort specification for the ordering of the results.
  220. * Falls back to the deprecated modifier if not specified. "$orderby"
  221. * @param array $arr 假如MQL中为{$sort:{"value.baseInfo.level":-1}则对应["value.baseInfo.level"=>-1]
  222. * @return MongoQueryOptionBuilder
  223. */
  224. public function sort($arr = array()) {
  225. $this->option[__FUNCTION__] = $arr;
  226. return $this;
  227. }
  228. // <editor-fold defaultstate="collapsed" desc="不常用或已经废弃的">
  229. /**
  230. * 不了解, 先不要使用
  231. * @deprecated since version 0
  232. * @param type $yes
  233. * @return $this
  234. */
  235. public function allowDiskUse($yes = true) {
  236. $this->option[__FUNCTION__] = $yes;
  237. return $this;
  238. }
  239. /**
  240. * 不了解, 先不要使用
  241. * @deprecated since version 0
  242. * @param type $yes
  243. * @return $this
  244. */
  245. public function allowPartialResults($yes = true) {
  246. $this->option[__FUNCTION__] = $yes;
  247. return $this;
  248. }
  249. /**
  250. * 不了解, 先不要使用
  251. * @deprecated since version 0
  252. * @param type $yes
  253. * @return $this
  254. */
  255. public function awaitData($yes = true) {
  256. $this->option[__FUNCTION__] = $yes;
  257. return $this;
  258. }
  259. /**
  260. * 返回值第一批的文档数,默认值为101,设置为0表示将建立光标,但不返回任何文档
  261. * @deprecated since version 0 不懂,先不要用
  262. * @param type $size
  263. * @return MongoQueryOptionBuilder
  264. */
  265. public function batchSize($size = 101) {
  266. $this->option[__FUNCTION__] = $size;
  267. return $this;
  268. }
  269. /**
  270. * 语言设置
  271. * @deprecated since version 0 这个太复杂还没研究,先不要用
  272. * @param array|object $collation
  273. * @return MongoQueryOptionBuilder
  274. */
  275. public function collation($collation = array()) {
  276. $this->option[__FUNCTION__] = $collation;
  277. return $this;
  278. }
  279. /**
  280. * 注释
  281. * @param type $msg
  282. * @return MongoQueryOptionBuilder
  283. */
  284. public function comment($msg = "默认注释") {
  285. $this->option[__FUNCTION__] = $msg;
  286. return $this;
  287. }
  288. /**
  289. * 尽最大努力下载数据,(从3.2+已经不再支持)
  290. * @deprecated since version mongodb 3.2+
  291. * @param type $yes
  292. * @return MongoQueryOptionBuilder
  293. */
  294. public function exhaust($yes = true) {
  295. $this->option[__FUNCTION__] = $yes;
  296. return $this;
  297. }
  298. /**
  299. * 不懂, 先不要用
  300. * @deprecated since version 0 在某个index的上限(不包含上限值)
  301. * @param array $arr
  302. * @return MongoQueryOptionBuilder
  303. */
  304. public function max($arr = array()) {
  305. $this->option[__FUNCTION__] = $arr;
  306. return $this;
  307. }
  308. /**
  309. * 不懂,先不要用
  310. * @deprecated since version 0 在某个index的下限(包含下限值)
  311. * @param array $arr
  312. * @return MongoQueryOptionBuilder
  313. */
  314. public function min($arr = array()) {
  315. $this->option[__FUNCTION__] = $arr;
  316. return $this;
  317. }
  318. /**
  319. * @deprecated since version 0 已经废弃
  320. * @param int $i
  321. * @throws \Exception
  322. */
  323. public function maxScan($i = 0) {
  324. throw new \Exception("Deprecated!");
  325. }
  326. /**
  327. * Determines whether to close the cursor after the first batch. Defaults to false.
  328. * @param bool $yes
  329. * @deprecated since version 0 不放心, 先不要用
  330. * @return MongoQueryOptionBuilder
  331. */
  332. public function singleBatch($yes = false) {
  333. $this->option[__FUNCTION__] = $yes;
  334. return $this;
  335. }
  336. /**
  337. * Determines whether to return the record identifier for each document.
  338. * If true, adds a top-level field to the returned documents. "$recordId"
  339. * @deprecated since version 0 这个感觉没啥用,也没测试过,先不要用
  340. * @param bool $yes
  341. * @return $this
  342. */
  343. public function showRecordId($yes = false) {
  344. $this->option[__FUNCTION__] = $yes;
  345. return $this;
  346. }
  347. /**
  348. * Returns a tailable cursor for a capped collection.
  349. * @deprecated since version 0 不懂,先不要用
  350. * @param type $yes
  351. * @return MongoQueryOptionBuilder
  352. */
  353. public function tailable($yes = false) {
  354. $this->option[__FUNCTION__] = $yes;
  355. return $this;
  356. }
  357. // </editor-fold>
  358. }