MongoOP.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. <?php
  2. /**
  3. * Mongodb操作类
  4. * Created by PhpStorm.
  5. * User: scstf
  6. * Date: 2018/9/13
  7. * Time: 15:35
  8. */
  9. namespace Biz\Db\Mongo;
  10. use MongoDB\Driver\Manager;
  11. use MongoDB\Driver\BulkWrite;
  12. use MongoDB\Driver\Exception\BulkWriteException;
  13. use MongoDB\Driver\Exception\Exception;
  14. use MongoDB\Driver\Query;
  15. use MongoDB\Driver\WriteConcern;
  16. class MongoOP
  17. {
  18. private $manager;
  19. private $bulk;
  20. private $dbName;
  21. private $instance;
  22. public function __construct($host, $port = 27017, $options = [])
  23. {
  24. $this->connect ($host, $port, $options);// or die('connection error:'.$this->connectString);
  25. }
  26. /**
  27. * 连接数据库
  28. * @param $host
  29. * @param int $port
  30. * @param array $options
  31. * @return Manager
  32. * @throws \Exception
  33. */
  34. private function connect($host, $port = 27017, $options = [])
  35. {
  36. if (!extension_loaded ('mongodb')) {
  37. return false;
  38. //throw new \Exception('没有安装mongodb扩展!');
  39. }
  40. $connectStr = "mongodb://{$host}:{$port}";
  41. if (isset($options['user']) && isset($options['password'])) {
  42. $user = $options['user'];
  43. $password = $options['password'];
  44. $connectStr = "mongodb://{$user}:{$password}@{$host}:{$port}";
  45. }
  46. if (isset($options['dbName'])) {
  47. $this->dbName = $options['dbName'];
  48. $connectStr .= '/' . $options['dbName'];
  49. }
  50. $this->bulk = new BulkWrite();
  51. $this->manager = new Manager($connectStr);
  52. return $this->instance = $this;
  53. }
  54. /**
  55. * 配置选中数据库
  56. * @param $dbName
  57. */
  58. public function setDbName($dbName)
  59. {
  60. $this->dbName = $dbName;
  61. }
  62. /**
  63. * 返回当前数据库名称
  64. * @return mixed
  65. */
  66. public function getDbName()
  67. {
  68. return $this->dbName;
  69. }
  70. /**
  71. * 插入数据
  72. * @param $key
  73. * @param $data
  74. * @param $sync
  75. * @return mixed
  76. */
  77. public function insert($key, array $data, $sync = true)
  78. {
  79. if (!$this->manager)
  80. return null;
  81. $manager = $this->manager;
  82. $writeConcern = new WriteConcern(1);
  83. $bulk = new BulkWrite(['ordered' => $sync]);//true为同步执行
  84. $bulk->insert ($data);
  85. try {
  86. return $result = $manager->executeBulkWrite ($this->dbName . ".{$key}", $bulk, $writeConcern) ? 1 : -1;//写入
  87. } catch (BulkWriteException $e) {
  88. $result = $e->getWriteResult ();
  89. // Check if the write concern could not be fulfilled
  90. if ($writeConcernError = $result->getWriteConcernError ()) {
  91. printf ("%s (%d): %s\n",
  92. $writeConcernError->getMessage (),
  93. $writeConcernError->getCode (),
  94. var_export ($writeConcernError->getInfo (), true)
  95. );
  96. }
  97. // Check if any write operations did not complete at all
  98. foreach ($result->getWriteErrors () as $writeError) {
  99. printf ("Operation#%d: %s (%d)\n",
  100. $writeError->getIndex (),
  101. $writeError->getMessage (),
  102. $writeError->getCode ()
  103. );
  104. }
  105. }
  106. return -1;
  107. }
  108. public function update($key, $id, $value, $data, $sync = true, $multi = true, $upsert = false)
  109. {
  110. $manager = $this->manager;
  111. if (!$manager)
  112. return null;
  113. $bulk = new BulkWrite(['ordered' => $sync]);
  114. $fill['$set'] = [];
  115. foreach ($data as $k => $v) {
  116. $item['$set'] = [$k => $v];
  117. $fill['$set'] = array_merge ($fill['$set'], $item['$set']);
  118. }
  119. $bulk->update (
  120. [$id => $value],
  121. $fill,
  122. ['multi' => $multi, 'upsert' => $upsert]
  123. );
  124. $ret = $manager->executeBulkWrite ($this->dbName . '.' . $key, $bulk);
  125. return $ret ? 1 : -1;
  126. }
  127. /**
  128. * 删除指定记录
  129. * @param $key
  130. * @param $id
  131. * @param $value
  132. * @param bool $sync
  133. * @param int $limit
  134. * @return int
  135. */
  136. public function remove($key, $id, $value, $sync = true, $limit = 0)
  137. {
  138. $manager = $this->manager;
  139. if (!$manager)
  140. return null;
  141. echo ',',$key,$id,$value;
  142. $bulk = new BulkWrite(['ordered' => $sync]);//true为同步执行
  143. $bulk->delete ([$id => $value], ['limit' => $limit]);//默认删除所有
  144. $ret = $manager->executeBulkWrite ($this->dbName . '.' . $key, $bulk);
  145. return $ret ? 1 : -1;
  146. }
  147. /**
  148. * 查询数据
  149. * @param $key
  150. * @param $condition
  151. * @param string $sort
  152. * @param int $asc
  153. * @param int $showId
  154. * @return array|bool
  155. * @throws Exception
  156. */
  157. public function search($key, $condition, $sort = '', $asc = 1, $showId = 0)
  158. {
  159. $manager = $this->manager;
  160. if (!$manager)
  161. return null;
  162. $filter = [];
  163. if (is_array ($condition))
  164. foreach ($condition as $k => $v) {
  165. $op = $this->convertOP ($v[0]);//转换操作符
  166. if (!$op) return false;
  167. $filter[$k] = [$op => $v[1]];
  168. }
  169. $options = [
  170. 'projection' => ['_id' => $showId], //不输出_id字段
  171. 'sort' => [$sort => $asc] //根据指定字段排序 1是升序,-1是降序
  172. ];
  173. if ($showId) {
  174. unset($options['projection']);
  175. }
  176. if (!$sort) {
  177. unset($options['sort']);
  178. }
  179. $query = new Query($filter, $options); //查询请求
  180. $list = $manager->executeQuery ($this->dbName . '.' . $key, $query); // 执行查询当前数据库下的$key集合
  181. return $list->toArray ();
  182. }
  183. public function get()
  184. {
  185. return $this;
  186. }
  187. /**
  188. * 转换操作符
  189. * @param $op
  190. * @return string
  191. */
  192. private function convertOP($op)
  193. {
  194. if (!is_string ($op)) return false;
  195. switch ($op) {
  196. case '>':
  197. case 'gt':
  198. return '$gt';
  199. case '<':
  200. case 'lt':
  201. return '$lt';
  202. case '>=':
  203. case 'gte':
  204. return '$gte';
  205. case '<=':
  206. case 'lte':
  207. return '$lte';
  208. case '!=':
  209. case '<>':
  210. case 'ne':
  211. case 'neq':
  212. case 'lgt':
  213. return '$ne';
  214. case 'in':
  215. return '$in';
  216. case 'nin':
  217. return '$nin';
  218. case 'eq':
  219. case '=':
  220. default:
  221. return '$eq';
  222. }
  223. }
  224. }