MongoUtil.php 12 KB

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