php操作MongoDB类实例

这篇文章主要介绍了php操作MongoDB类的方法,实例分析了仿照CI实现的MongoDB类及其操作技巧,需要的朋友可以参考下。

本文实例讲述了php操作MongoDB类的方法,分享给大家供大家参考,具体如下:

1. MyMongo.php文件:

  1. <?php
  2. /**
  3. * 仿写CI的MongoDB
  4. * @author sparkHuang 2011-11-03
  5. *
  6. */
  7. class MyMongo {
  8. private $mongo_config = "mongo_config.php";
  9. private $connection;
  10. private $db;
  11. private $mongo_connect_string;
  12. private $host;
  13. private $port;
  14. private $user;
  15. private $pass;
  16. private $dbname;
  17. private $persist;
  18. private $persist_key;
  19. private $selects = array();
  20. private $wheres = array();
  21. private $sorts = array();
  22. private $limit = 999999;
  23. private $offset = 0;
  24. public function __construct() {
  25. if ( ! class_exists('Mongo')) {
  26. $this->log_error("The MongoDB PECL extentiosn has not been installed or enabled.");
  27. exit;
  28. }
  29. $this->connection_string();
  30. $this->connect();
  31. }
  32. /**
  33. * 更改数据库
  34. *
  35. */
  36. public function switch_db($database = '') {
  37. if (emptyempty($database)) {
  38. $this->log_error("To switch MongoDB databases, a new database name must be specified");
  39. exit;
  40. }
  41. $this->dbname = $database;
  42. try {
  43. $this->db = $this->connection->{$this->dbname};
  44. return true;
  45. } catch(Exception $e) {
  46. $this->log_error("Unable to switch Mongo Databases: {$e->getMessage()}");
  47. exit;
  48. }
  49. }
  50. /**
  51. * 设置select字段
  52. *
  53. */
  54. public function select($includs = array(), $excludes = array()) {
  55. if ( ! is_array($includs)) {
  56. $includs = (array)$includs;
  57. }
  58. if ( ! is_array($excludes)) {
  59. $excludes = (array)$excludes;
  60. }
  61. if ( ! emptyempty($includs)) {
  62. foreach ($includs as $col) {
  63. $this->selects[$col] = 1;
  64. }
  65. } else {
  66. foreach ($excludes as $col) {
  67. $this->selects[$col] = 0;
  68. }
  69. }
  70. return($this);
  71. }
  72. /**
  73. * where条件查询判断
  74. *
  75. * @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar');
  76. *
  77. */
  78. public function where($wheres = array()) {
  79. if ( ! is_array($wheres)) {
  80. $wheres = (array)$wheres;
  81. }
  82. if ( ! emptyempty($wheres)) {
  83. foreach($wheres as $wh => $val) {
  84. $this->wheres[$wh] = $val;
  85. }
  86. }
  87. return($this);
  88. }
  89. /**
  90. * where ... in .. 条件查询判断
  91. *
  92. * @usage = $this->mongo_db->where_in('foo', array('bar', 'zoo'))->get('foobar');
  93. *
  94. */
  95. public function where_in($field = '', $in = array()) {
  96. $this->where_init($field);
  97. $this->wheres[$field]['$in'] = $in;
  98. return($this);
  99. }
  100. /**
  101. * where ... not in .. 条件查询判断
  102. *
  103. * @usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo'))->get('foobar');
  104. *
  105. */
  106. public function where_not_in($field = '', $in = array()) {
  107. $this->where_init($field);
  108. $this->wheres[$field]['$nin'] = $in;
  109. return($this);
  110. }
  111. /**
  112. * where ... $field > $x .. 条件查询判断
  113. *
  114. * @usage = $this->mongo_db->where_gt('foo', 20)->get('foobar');
  115. *
  116. */
  117. public function where_gt($field = '', $x) {
  118. $this->where_init($field);
  119. $this->wheres[$field]['$gt'] = $x;
  120. return($this);
  121. }
  122. /**
  123. * where ... $field >= $x .. 条件查询判断
  124. *
  125. * @usage = $this->mongo_db->where_gte('foo', 20)->get('foobar');
  126. *
  127. */
  128. public function where_gte($field = '', $x) {
  129. $this->where_init($field);
  130. $this->wheres[$field]['$gte'] = $x;
  131. return($this);
  132. }
  133. /**
  134. * where ... $field < $x .. 条件查询判断
  135. *
  136. * @usage = $this->mongo_db->where_lt('foo', 20)->get('foobar');
  137. *
  138. */
  139. public function where_lt($field = '', $x) {
  140. $this->where_init($field);
  141. $this->wheres[$field]['$lt'] = $x;
  142. return($this);
  143. }
  144. /**
  145. * where ... $field <= $x .. 条件查询判断
  146. *
  147. * @usage = $this->mongo_db->where_lte('foo', 20)->get('foobar');
  148. *
  149. */
  150. public function where_lte($field = '', $x) {
  151. $this->where_init($field);
  152. $this->wheres[$field]['$lte'] = $x;
  153. return($this);
  154. }
  155. /**
  156. * where ... $field >= $x AND $field <= $y .. 条件查询判断
  157. *
  158. * @usage = $this->mongo_db->where_between('foo', 20, 30)->get('foobar');
  159. *
  160. */
  161. public function where_between($field = '', $x, $y) {
  162. $this->where_init($field);
  163. $this->wheres[$field]['$gte'] = $x;
  164. $this->wheres[$field]['$lte'] = $y;
  165. return($this);
  166. }
  167. /**
  168. * where ... $field > $x AND $field < $y .. 条件查询判断
  169. *
  170. * @usage = $this->mongo_db->where_between_ne('foo', 20, 30)->get('foobar');
  171. *
  172. */
  173. public function where_between_ne($field = '', $x, $y) {
  174. $this->where_init($field);
  175. $this->wheres[$field]['$gt'] = $x;
  176. $this->wheres[$field]['$lt'] = $y;
  177. return($this);
  178. }
  179. /**
  180. * where ... $field <> $x .. 条件查询判断
  181. *
  182. * @usage = $this->mongo_db->where_ne('foo', 20)->get('foobar');
  183. *
  184. */
  185. public function where_ne($field = '', $x) {
  186. $this->where_init($field);
  187. $this->wheres[$field]['$ne'] = $x;
  188. return($this);
  189. }
  190. /**
  191. * where ... or .. 条件查询判断
  192. *
  193. * @usage = $this->mongo_db->where_or('foo', array('foo', 'bar'))->get('foobar');
  194. *
  195. */
  196. public function where_or($field = '', $values) {
  197. $this->where_init($field);
  198. $this->wheres[$field]['$or'] = $values;
  199. return($this);
  200. }
  201. /**
  202. * where ... and .. 条件查询判断
  203. *
  204. * @usage = $this->mongo_db->where_and( array ( 'foo' => 1, 'b' => 'someexample' );
  205. */
  206. public function where_and( $elements_values = array() ) {
  207. foreach ( $elements_values as $element => $val ) {
  208. $this->wheres[$element] = $val;
  209. }
  210. return($this);
  211. }
  212. /**
  213. * where $field % $num = $result
  214. *
  215. * @usage = $this->mongo_db->where_mod( 'foo', 10, 1 );
  216. */
  217. public function where_mod( $field, $num, $result ) {
  218. $this->where_init($field);
  219. $this->wheres[$field]['$mod'] = array($num, $result);
  220. return($this);
  221. }
  222. /**
  223. * where size
  224. *
  225. * Get the documents where the size of a field is in a given $size int
  226. *
  227. * @usage : $this->mongo_db->where_size('foo', 1)->get('foobar');
  228. */
  229. public function where_size($field = "", $size = "") {
  230. $this->where_init($field);
  231. $this->wheres[$field]['$size'] = $size;
  232. return ($this);
  233. }
  234. /**
  235. * like条件查询(PHP中定义MongoRegex类实现)
  236. *
  237. * @usage : $this->mongo_db->like('foo', 'bar', 'im', false, false)->get();
  238. */
  239. public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = true, $enable_end_wildcard = true) {
  240. $field = (string)$field;
  241. $this->where_init($field);
  242. $value = (string)$value;
  243. $value = quotmeta($value);
  244. if (true !== $enable_start_wildcard) {
  245. $value = "^".$value;
  246. }
  247. if (true !== $enable_end_wildcard) {
  248. $value .= "$";
  249. }
  250. $regex = "/$value/$flags";
  251. $this->wheres[$field] = new MongoRegex($regex);
  252. return($this);
  253. }
  254. /**
  255. * order排序( 1 => ASC, -1 => DESC)
  256. *
  257. * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->order_by(array("age" => 1));
  258. */
  259. public function order_by($fields = array()) {
  260. foreach($fields as $col => $val) {
  261. if ($val == -1 || $val == false || strtolower($val) == "desc") {
  262. $this->sorts[$col] = -1;
  263. } else {
  264. $this->sorts[$col] = 1;
  265. }
  266. }
  267. return($this);
  268. }
  269. /**
  270. * limit
  271. *
  272. * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->limit(10);
  273. */
  274. public function limit($x = 999999) {
  275. if ($x !== NULL && is_numeric($x) && $x >= 1) {
  276. $this->limit = (int)$x;
  277. }
  278. return($this);
  279. }
  280. /**
  281. * offset
  282. *
  283. * @usage: $this->mongo_db->get_where('foo', array('name' => 'tom'))->offset(10);
  284. */
  285. public function offset($x = 0) {
  286. if($x !== NULL && is_numeric($x) && $x >= 1) {
  287. $this->offset = (int) $x;
  288. }
  289. return($this);
  290. }
  291. /**
  292. * get_where
  293. *
  294. * @usage: $this->mongo_db->get_where('foo', array('bar' => 'something'));
  295. */
  296. public function get_where($collection = "", $where = array(), $limit = 999999) {
  297. return($this->where($where)->limit($limit)->get($collection));
  298. }
  299. /**
  300. * get
  301. *
  302. * @usage: $this->mongo_db->where(array('name' => 'tom'))->get('foo');
  303. */
  304. public function get($collection) {
  305. if (emptyempty($collection)) {
  306. $this->log_error("In order to retreive documents from MongoDB, a collection name must be passed");
  307. exit;
  308. }
  309. $results = array();
  310. $results = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int)$this->limit)->skip((int)$this->offset)->sort($this->sorts);
  311. $returns = array();
  312. foreach($results as $result) {
  313. $returns[] = $result;
  314. }
  315. $this->clear();
  316. return($returns);
  317. }
  318. /**
  319. * count
  320. *
  321. * @usage: $this->db->get_where('foo', array('name' => 'tom'))->count('foo');
  322. */
  323. public function count($collection) {
  324. if (emptyempty($collection)) {
  325. $this->log_error("In order to retreive documents from MongoDB, a collection name must be passed");
  326. exit;
  327. }
  328. $count = $this->db->{$collection}->find($this->wheres)->limit((int)$this->limit)->skip((int)$this->offset)->count();
  329. $this->clear();
  330. return($count);
  331. }
  332. /**
  333. * insert
  334. *
  335. * @usage: $this->mongo_db->insert('foo', array('name' => 'tom'));
  336. */
  337. public function insert($collection = "", $data = array()) {
  338. if (emptyempty($collection)) {
  339. $this->log_error("No Mongo collection selected to delete from");
  340. exit;
  341. }
  342. if (count($data) == 0 || ! is_array($data)) {
  343. $this->log_error("Nothing to insert into Mongo collection or insert is not an array");
  344. exit;
  345. }
  346. try {
  347. $this->db->{$collection}->insert($data, array('fsync' => true));
  348. if (isset($data['_id'])) {
  349. return($data['_id']);
  350. } else {
  351. return(false);
  352. }
  353. } catch(MongoCursorException $e) {
  354. $this->log_error("Insert of data into MongoDB failed: {$e->getMessage()}");
  355. exit;
  356. }
  357. }
  358. /**
  359. * update : 利用MongoDB的 $set 实现
  360. *
  361. * @usage : $this->mongo_db->where(array('name' => 'tom'))->update('foo', array('age' => 24))
  362. */
  363. public function update($collection = "", $data = array()) {
  364. if (emptyempty($collection)) {
  365. $this->log_error("No Mongo collection selected to delete from");
  366. exit;
  367. }
  368. if (count($data) == 0 || ! is_array($data)) {
  369. $this->log_error("Nothing to update in Mongo collection or update is not an array");
  370. exit;
  371. }
  372. try {
  373. $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => true, 'multiple' => false)); //注意: multiple为false
  374. return(true);
  375. } catch(MongoCursorException $e) {
  376. $this->log_error("Update of data into MongoDB failed: {$e->getMessage()}");
  377. exit;
  378. }
  379. }
  380. /**
  381. * update_all : 利用MongoDB的 $set 实现
  382. *
  383. * @usage : $this->mongo_db->where(array('name' => 'tom'))->update_all('foo', array('age' => 24));
  384. */
  385. public function update_all($collection = "", $data = array()) {
  386. if (emptyempty($collection)) {
  387. $this->log_error("No Mongo collection selected to delete from");
  388. exit;
  389. }
  390. if (count($data) == 0 || ! is_array($data)) {
  391. $this->log_error("Nothing to update in Mongo collection or update is not an array");
  392. exit;
  393. }
  394. try {
  395. $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => true, 'multiple' => true)); //注意: multiple为true
  396. return(true);
  397. } catch(MongoCursorException $e) {
  398. $this->log_error("Update of data into MongoDB failed: {$e->getMessage()}");
  399. exit;
  400. }
  401. }
  402. /**
  403. * delete
  404. *
  405. * @usage : $this->mongo_db->where(array('name' => 'tom'))->delete('foo');
  406. */
  407. public function delete($collection = "") {
  408. if (emptyempty($collection)) {
  409. $this->log_error("No Mongo collection selected to delete from");
  410. exit;
  411. }
  412. try {
  413. $this->db->{$collection}->remove($this->wheres, array('fsync' => true, 'justOne' => true)); //注意justOne为true;
  414. } catch(MongoCursorException $e) {
  415. $this->log_error("Delete of data into MongoDB failed: {$e->getMessage()}");
  416. exit;
  417. }
  418. }
  419. /**
  420. * delete_all
  421. *
  422. * @usage : $this->mongo_db->where(array('name' => 'tom'))->delete_all('foo');
  423. */
  424. public function delete_all($collection = "") {
  425. if (emptyempty($collection)) {
  426. $this->log_error("No Mongo collection selected to delete from");
  427. exit;
  428. }
  429. try {
  430. $this->db->{$collection}->remove($this->wheres, array('fsync' => true, 'justOne' => false)); //注意justOne为false;
  431. } catch(MongoCursorException $e) {
  432. $this->log_error("Delete of data into MongoDB failed: {$e->getMessage()}");
  433. exit;
  434. }
  435. }
  436. /**
  437. * add_index
  438. *
  439. * @usage : $this->mongo_db->add_index('foo', array('first_name' => 'ASC', 'last_name' => -1), array('unique' => true)));
  440. */
  441. public function add_index($collection, $keys = array(), $options = array()) {
  442. if (emptyempty($collection)) {
  443. $this->log_error("No Mongo collection specified to add index to");
  444. exit;
  445. }
  446. if (emptyempty($keys) || ! is_array($keys)) {
  447. $this->log_error("Index could not be created to MongoDB Collection because no keys were specified");
  448. exit;
  449. }
  450. foreach($keys as $col => $val) {
  451. if ($val == -1 || $val == false || strtolower($val) == 'desc') {
  452. $keys[$col] = -1;
  453. } else {
  454. $keys[$col] = 1;
  455. }
  456. }
  457. //在此没有对$options数组的有效性进行验证
  458. if (true == $this->db->{$collection}->ensureIndex($keys, $options)) {
  459. $this->clear();
  460. return($this);
  461. } else {
  462. $this->log_error("An error occured when trying to add an index to MongoDB Collection");
  463. exit;
  464. }
  465. }
  466. /**
  467. * remove_index
  468. *
  469. * @usage : $this->mongo_db->remove_index('foo', array('first_name' => 'ASC', 'last_name' => -1))
  470. */
  471. public function remove_index($collection = "", $keys = array()) {
  472. if (emptyempty($collection)) {
  473. $this->log_error("No Mongo collection specified to add index to");
  474. exit;
  475. }
  476. if (emptyempty($keys) || ! is_array($keys)) {
  477. $this->log_error("Index could not be created to MongoDB Collection because no keys were specified");
  478. exit;
  479. }
  480. if ($this->db->{$collection}->deleteIndex($keys)) {
  481. $this->clear();
  482. return($this);
  483. } else {
  484. $this->log_error("An error occured when trying to add an index to MongoDB Collection");
  485. exit;
  486. }
  487. }
  488. /**
  489. * remove_all_index
  490. *
  491. * @usage : $this->mongo_db->remove_all_index('foo', array('first_name' => 'ASC', 'last_name' => -1))
  492. */
  493. public function remove_all_index($collection = "", $keys = array()) {
  494. if (emptyempty($collection)) {
  495. $this->log_error("No Mongo collection specified to add index to");
  496. exit;
  497. }
  498. if (emptyempty($keys) || ! is_array($keys)) {
  499. $this->log_error("Index could not be created to MongoDB Collection because no keys were specified");
  500. exit;
  501. }
  502. if ($this->db->{$collection}->deleteIndexes($keys)) {
  503. $this->clear();
  504. return($this);
  505. } else {
  506. $this->log_error("An error occured when trying to add an index to MongoDB Collection");
  507. exit;
  508. }
  509. }
  510. /**
  511. * list_indexes
  512. *
  513. * @usage : $this->mongo_db->list_indexes('foo');
  514. */
  515. public function list_indexes($collection = "") {
  516. if (emptyempty($collection)) {
  517. $this->log_error("No Mongo collection specified to add index to");
  518. exit;
  519. }
  520. return($this->db->{$collection}->getIndexInfo());
  521. }
  522. /**
  523. * drop_collection
  524. *
  525. * @usage : $this->mongo_db->drop_collection('foo');
  526. */
  527. public function drop_collection($collection = "") {
  528. if (emptyempty($collection)) {
  529. $this->log_error("No Mongo collection specified to add index to");
  530. exit;
  531. }
  532. $this->db->{$collection}->drop();
  533. return(true);
  534. }
  535. /**
  536. * 生成连接MongoDB 参数字符串
  537. *
  538. */
  539. private function connection_string() {
  540. include_once($this->mongo_config);
  541. $this->host = trim($config['host']);
  542. $this->port = trim($config['port']);
  543. $this->user = trim($config['user']);
  544. $this->pass = trim($config['pass']);
  545. $this->dbname = trim($config['dbname']);
  546. $this->persist = trim($config['persist']);
  547. $this->persist_key = trim($config['persist_key']);
  548. $connection_string = "mongodb://";
  549. if (emptyempty($this->host)) {
  550. $this->log_error("The Host must be set to connect to MongoDB");
  551. exit;
  552. }
  553. if (emptyempty($this->dbname)) {
  554. $this->log_error("The Database must be set to connect to MongoDB");
  555. exit;
  556. }
  557. if ( ! emptyempty($this->user) && ! emptyempty($this->pass)) {
  558. $connection_string .= "{$this->user}:{$this->pass}@";
  559. }
  560. if ( isset($this->port) && ! emptyempty($this->port)) {
  561. $connection_string .= "{$this->host}:{$this->port}";
  562. } else {
  563. $connection_string .= "{$this->host}";
  564. }
  565. $this->connection_string = trim($connection_string);
  566. }
  567. /**
  568. * 连接MongoDB 获取数据库操作句柄
  569. *
  570. */
  571. private function connect() {
  572. $options = array();
  573. if (true === $this->persist) {
  574. $options['persist'] = isset($this->persist_key) && ! emptyempty($this->persist_key) ? $this->persist_key : "ci_mongo_persist";
  575. }
  576. try {
  577. $this->connection = new Mongo($this->connection_string, $options);
  578. $this->db = $this->connection->{$this->dbname};
  579. return ($this);
  580. } catch (MongoConnectionException $e) {
  581. $this->log_error("Unable to connect to MongoDB: {$e->getMessage()}");
  582. }
  583. }
  584. /**
  585. * 初始化清理部分成员变量
  586. *
  587. */
  588. private function clear() {
  589. $this->selects = array();
  590. $this->wheres = array();
  591. $this->limit = NULL;
  592. $this->offset = NULL;
  593. $this->sorts = array();
  594. }
  595. /**
  596. * 依据字段名初始化处理$wheres数组
  597. *
  598. */
  599. private function where_init($param) {
  600. if ( ! isset($this->wheres[$param])) {
  601. $this->wheres[$param] = array();
  602. }
  603. }
  604. /**
  605. * 错误记录
  606. *
  607. */
  608. private function log_error($msg) {
  609. $msg = "[Date: ".date("Y-m-i H:i:s")."] ".$msg;
  610. @file_put_contents("./error.log", print_r($msg."\n", true), FILE_APPEND);
  611. }
  612. }
  613. /* End of MyMongo.php */

2. mongo_config.php配置文件:

  1. <?php
  2. $config["host"] = "localhost";
  3. $config["user"] = "";
  4. $config["pass"] = "";
  5. $config["port"] = 27017;
  6. $config["dbname"] = "test";
  7. $config['persist'] = TRUE;
  8. $config['persist_key'] = 'ci_mongo_persist';
  9. /*End of mongo_config.php*/

3. MyMongoDemo.php文件:

  1. <?php
  2. include_once("MyMongo.php");
  3. $conn = new MyMongo();
  4. //删除所有记录
  5. $conn->delete_all("blog");
  6. //插入第一条记录
  7. $value = array("name" => "小明", "age" => 25, "addr" => array("country" => "中国", "province" => "广西", "city" => "桂林"));
  8. $conn->insert("blog", $value);
  9. var_dump($conn->select(array("name", "age"))->get("blog"));
  10. var_dump($conn->get("blog"));
  11. /* End of MyMongoDemo.php */