php实现的mongodb操作类实例

这篇文章主要介绍了php实现的mongodb操作类,较为详细的分析了php针对mongodb数据库操作的各种常用技巧,并将其封装进一个完整的类文件中以便于调用,非常具有实用价值,需要的朋友可以参考下.

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

  1. <?php
  2. /*
  3. * To change this template, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. class mongo_db {
  7. private $config;
  8. private $connection;
  9. private $db;
  10. private $connection_string;
  11. private $host;
  12. private $port;
  13. private $user;
  14. private $pass;
  15. private $dbname;
  16. private $persist;
  17. private $persist_key;
  18. private $selects = array();
  19. private $wheres = array();
  20. private $sorts = array();
  21. private $limit = 999999;
  22. private $offset = 0;
  23. private $timeout = 200;
  24. private $key = 0;
  25. /**
  26. *
  27. * CONSTRUCTOR *
  28. *
  29. * Automatically check if the Mongo PECL extension has been
  30. installed/enabled.
  31. * Generate the connection string and establish a connection
  32. to the MongoDB.
  33. */
  34. public function __construct() {
  35. if((IS_NOSQL != 1)){
  36. return;
  37. }
  38. if (!class_exists('Mongo')) {
  39. //$this->error("The MongoDB PECL extension has not been installed or enabled", 500);
  40. }
  41. $configs =wxcity_base::load_config("cache","mongo_db");
  42. $num = count($configs['connect']);
  43. $this->timeout = trim($configs['timeout']);
  44. $keys = wxcity_base::load_config('double');
  45. $this->key = $keys['mongo_db'];
  46. $this->config = $configs['connect'][$this->key];
  47. $status = $this->connect();
  48. if($status == false)
  49. {
  50. for($i = 1; $i < $num; $i++)
  51. {
  52. $n = $this->key + $i;
  53. $key = $n >= $num ? $n - $num : $n;
  54. $this->config = $configs['connect'][$key];
  55. $status = $this->connect();
  56. if($status!=false)
  57. {
  58. $keys['mongo_db'] = $key ;
  59. $this->key = $key;
  60. $data = "<?php\nreturn ".var_export($keys, true).";\n?>";
  61. file_put_contents(WHTY_PATH.'configs/double.php', $data, LOCK_EX);
  62. break;
  63. }
  64. }
  65. }
  66. if($status==false)
  67. {
  68. die('mongoDB not connect');
  69. }
  70. }
  71. function __destruct() {
  72. if((IS_NOSQL != 1)){
  73. return;
  74. }
  75. if($this->connection)
  76. {
  77. $this->connection->close();
  78. }
  79. }
  80. /**
  81. *
  82. * CONNECT TO MONGODB *
  83. *
  84. * Establish a connection to MongoDB using
  85. the connection string generated in
  86. * the connection_string() method.
  87. If 'mongo_persist_key' was set to true in the
  88. * config file, establish a persistent connection.
  89. We allow for only the 'persist'
  90. * option to be set because we want to
  91. establish a connection immediately.
  92. */
  93. private function connect() {
  94. $this->connection_string();
  95. $options = array('connect'=>true,'timeout'=>$this->timeout);
  96. try {
  97. $this->connection = new Mongo($this->connection_string, $options);
  98. $this->db = $this->connection->{$this->dbname};
  99. return($this);
  100. } catch (MongoConnectionException $e) {
  101. return false;
  102. }
  103. }
  104. /**
  105. *
  106. * BUILD CONNECTION STRING *
  107. *
  108. * Build the connection string from the config file.
  109. */
  110. private function connection_string() {
  111. $this->host = trim($this->config['hostname']);
  112. $this->port = trim($this->config['port']);
  113. $this->user = trim($this->config['username']);
  114. $this->pass = trim($this->config['password']);
  115. $this->dbname = trim($this->config['database']);
  116. $this->persist = trim($this->config['autoconnect']);
  117. $this->persist_key = trim($this->config['mongo_persist_key']);
  118. $connection_string = "mongodb://";
  119. if (emptyempty($this->host)) {
  120. $this->error("The Host must be set to connect to MongoDB", 500);
  121. } if (emptyempty($this->dbname)) {
  122. $this->error("The Database must be set to connect to MongoDB", 500);
  123. } if (!emptyempty($this->user) && !emptyempty($this->pass)) {
  124. $connection_string .= "{$this->user}:{$this->pass}@";
  125. } if (isset($this->port) && !emptyempty($this->port)) {
  126. $connection_string .= "{$this->host}:{$this->port}";
  127. } else {
  128. $connection_string .= "{$this->host}";
  129. } $this->connection_string = trim($connection_string);
  130. }
  131. /**
  132. *
  133. * Switch_db *
  134. *
  135. * Switch from default database to a different db
  136. */
  137. public function switch_db($database = '') {
  138. if (emptyempty($database)) {
  139. $this->error("To switch MongoDB databases, a new database name must be specified", 500);
  140. } $this->dbname = $database;
  141. try {
  142. $this->db = $this->connection->{$this->dbname};
  143. return(TRUE);
  144. } catch (Exception $e) {
  145. $this->error("Unable to switch Mongo Databases: {$e->getMessage()}", 500);
  146. }
  147. }
  148. /**
  149. *
  150. * SELECT FIELDS *
  151. *
  152. * Determine which fields to include OR which to
  153. exclude during the query process.
  154. * Currently, including and excluding at
  155. the same time is not available, so the
  156. * $includes array will take precedence over
  157. the $excludes array.
  158. If you want to
  159. * only choose fields to exclude,
  160. leave $includes an empty array().
  161. *
  162. * @usage: $this->mongo_db->select(array('foo', 'bar'))->get('foobar');
  163. */
  164. public function select($includes = array(), $excludes = array()) {
  165. if (!is_array($includes)) {
  166. $includes = array();
  167. }
  168. if (!is_array($excludes)) {
  169. $excludes = array();
  170. }
  171. if (!emptyempty($includes)) {
  172. foreach ($includes as $col) {
  173. $this->selects[$col] = 1;
  174. }
  175. } else {
  176. foreach ($excludes as $col) {
  177. $this->selects[$col] = 0;
  178. }
  179. } return($this);
  180. }
  181. /**
  182. *
  183. * WHERE PARAMETERS *
  184. *
  185. * Get the documents based on these
  186. search parameters. The $wheres array should
  187. * be an associative array with the field
  188. as the key and the value as the search
  189. * criteria. *
  190. * @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar');
  191. */
  192. public function where($wheres = array()) {
  193. foreach ((array)$wheres as $wh => $val) {
  194. $this->wheres[$wh] = $val;
  195. } return($this);
  196. }
  197. /**
  198. *
  199. * WHERE_IN PARAMETERS *
  200. *
  201. * Get the documents where the value
  202. of a $field is in a given $in array().
  203. *
  204. * @usage = $this->mongo_db->where_in('foo', array('bar', 'zoo', 'blah'))->get('foobar');
  205. */
  206. public function where_in($field = "", $in = array()) {
  207. $this->where_init($field);
  208. $this->wheres[$field]['$in'] = $in;
  209. return($this);
  210. }
  211. /**
  212. *
  213. * WHERE_NOT_IN PARAMETERS *
  214. *
  215. * Get the documents where the value of
  216. a $field is not in a given $in array().
  217. *
  218. * @usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo', 'blah'))->get('foobar');
  219. */
  220. public function where_not_in($field = "", $in = array()) {
  221. $this->where_init($field);
  222. $this->wheres[$field]['$nin'] = $in;
  223. return($this);
  224. }
  225. /**
  226. *
  227. * WHERE GREATER THAN PARAMETERS *
  228. *
  229. * Get the documents where the value of
  230. a $field is greater than $x
  231. *
  232. * @usage = $this->mongo_db->where_gt('foo', 20);
  233. */
  234. public function where_gt($field = "", $x) {
  235. $this->where_init($field);
  236. $this->wheres[$field]['$gt'] = $x;
  237. return($this);
  238. }
  239. /**
  240. *
  241. * WHERE GREATER THAN OR EQUAL TO PARAMETERS *
  242. *
  243. * Get the documents where the value of a $field is greater than or equal to $x
  244. *
  245. * @usage = $this->mongo_db->where_gte('foo', 20);
  246. */
  247. public function where_gte($field = "", $x) {
  248. $this->where_init($field);
  249. $this->wheres[$field]['$gte'] = $x;
  250. return($this);
  251. }
  252. /**
  253. *
  254. * WHERE LESS THAN PARAMETERS *
  255. *
  256. * Get the documents where the value of
  257. a $field is less than $x
  258. *
  259. * @usage = $this->mongo_db->where_lt('foo', 20);
  260. */
  261. public function where_lt($field = "", $x) {
  262. $this->where_init($field);
  263. $this->wheres[$field]['$lt'] = $x;
  264. return($this);
  265. }
  266. /**
  267. *
  268. * WHERE LESS THAN OR EQUAL TO PARAMETERS *
  269. *
  270. * Get the documents where the value of
  271. a $field is less than or equal to $x
  272. *
  273. * @usage = $this->mongo_db->where_lte('foo', 20);
  274. */
  275. public function where_lte($field = "", $x) {
  276. $this->where_init($field);
  277. $this->wheres[$field]['$lte'] = $x;
  278. return($this);
  279. }
  280. /**
  281. *
  282. * WHERE BETWEEN PARAMETERS *
  283. *
  284. * Get the documents where the value of
  285. a $field is between $x and $y
  286. *
  287. * @usage = $this->mongo_db->where_between('foo', 20, 30);
  288. */
  289. public function where_between($field = "", $x, $y) {
  290. $this->where_init($field);
  291. $this->wheres[$field]['$gte'] = $x;
  292. $this->wheres[$field]['$lte'] = $y;
  293. return($this);
  294. }
  295. /**
  296. *
  297. * WHERE BETWEEN AND NOT EQUAL TO PARAMETERS *
  298. *
  299. * Get the documents where the value of
  300. a $field is between but not equal to $x and $y
  301. *
  302. * @usage = $this->mongo_db->where_between_ne('foo', 20, 30);
  303. */
  304. public function where_between_ne($field = "", $x, $y) {
  305. $this->where_init($field);
  306. $this->wheres[$field]['$gt'] = $x;
  307. $this->wheres[$field]['$lt'] = $y;
  308. return($this);
  309. }
  310. /**
  311. *
  312. * WHERE NOT EQUAL TO PARAMETERS *
  313. *
  314. * Get the documents where the value of
  315. a $field is not equal to $x
  316. *
  317. * @usage = $this->mongo_db->where_between('foo', 20, 30);
  318. */
  319. public function where_ne($field = "", $x) {
  320. $this->where_init($field);
  321. $this->wheres[$field]['$ne'] = $x;
  322. return($this);
  323. }
  324. /**
  325. *
  326. * WHERE OR *
  327. *
  328. * Get the documents where the value of
  329. a $field is in one or more values
  330. *
  331. * @usage = $this->mongo_db->where_or('foo', array( 'foo', 'bar', 'blegh' );
  332. */
  333. public function where_or($field = "", $values) {
  334. $this->where_init($field);
  335. $this->wheres[$field]['$or'] = $values;
  336. return($this);
  337. }
  338. /**
  339. *
  340. * WHERE AND *
  341. *
  342. * Get the documents where the elements match
  343. the specified values *
  344. * @usage = $this->mongo_db->where_and( array ( 'foo' => 1, 'b' => 'someexample' );
  345. */
  346. public function where_and($elements_values = array()) {
  347. foreach ((array)$elements_values as $element => $val) {
  348. $this->wheres[$element] = $val;
  349. } return($this);
  350. }
  351. /**
  352. *
  353. * WHERE MOD *
  354. *
  355. * Get the documents where $field % $mod = $result *
  356. * @usage = $this->mongo_db->where_mod( 'foo', 10, 1 );
  357. */
  358. public function where_mod($field, $num, $result) {
  359. $this->where_init($field);
  360. $this->wheres[$field]['$mod'] = array($num, $result);
  361. return($this);
  362. }
  363. /** * * Where size * * * Get the documents where the size of a field is in a given $size int * * @usage : $this->mongo_db->where_size('foo', 1)->get('foobar'); */
  364. public function where_size($field = "", $size = "") {
  365. $this->_where_init($field);
  366. $this->wheres[$field]['$size'] = $size;
  367. return ($this);
  368. }
  369. /**
  370. *
  371. * LIKE PARAMETERS *
  372. *
  373. * Get the documents where the (string) value of
  374. a $field is like a value. The defaults
  375. * allow for a case-insensitive search. *
  376. * @param $flags
  377. * Allows for the typical regular expression flags:
  378. * i = case insensitive
  379. * m = multiline
  380. * x = can contain comments
  381. * l = locale
  382. * s = dotall, "." matches everything, including newlines
  383. * u = match unicode
  384. *
  385. * @param $enable_start_wildcard
  386. * If set to anything other than TRUE, a starting line character "^" will be prepended
  387. * to the search value, representing only searching for a value at the start of
  388. * a new line.
  389. * * @param $enable_end_wildcard
  390. * If set to anything other than TRUE, an ending line character "$" will be appended
  391. * to the search value, representing only searching for a value at the end of
  392. * a line.
  393. *
  394. * @usage = $this->mongo_db->like('foo', 'bar', 'im', FALSE, TRUE);
  395. */
  396. public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = TRUE, $enable_end_wildcard = TRUE) {
  397. $field = (string) trim($field);
  398. $this->where_init($field);
  399. $value = (string) trim($value);
  400. $value = quotemeta($value);
  401. if ($enable_start_wildcard !== TRUE) {
  402. $value = "^" . $value;
  403. } if ($enable_end_wildcard !== TRUE) {
  404. $value .= "$";
  405. } $regex = "/$value/$flags";
  406. $this->wheres[$field] = new MongoRegex($regex);
  407. return($this);
  408. }
  409. public function wheres($where){
  410. $this->wheres = $where;
  411. }
  412. /**
  413. *
  414. * ORDER BY PARAMETERS *
  415. *
  416. * Sort the documents based on the parameters passed.
  417. To set values to descending order,
  418. * you must pass values of either -1, FALSE,
  419. 'desc', or 'DESC', else they will be
  420. * set to 1 (ASC).
  421. *
  422. * @usage = $this->mongo_db->where_between('foo', 20, 30);
  423. */
  424. public function order_by($fields = array()) {
  425. if (!is_array($fields) || !count($fields)) return ;
  426. foreach ($fields as $col => $val) {
  427. if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') {
  428. $this->sorts[$col] = -1;
  429. } else {
  430. $this->sorts[$col] = 1;
  431. }
  432. } return($this);
  433. }
  434. /**
  435. *
  436. * LIMIT DOCUMENTS *
  437. *
  438. * Limit the result set to $x number of documents *
  439. * @usage = $this->mongo_db->limit($x);
  440. */
  441. public function limit($x = 99999) {
  442. if ($x !== NULL && is_numeric($x) && $x >= 1) {
  443. $this->limit = (int) $x;
  444. } return($this);
  445. }
  446. /**
  447. *
  448. * OFFSET DOCUMENTS *
  449. *
  450. * Offset the result set to skip $x number of documents
  451. *
  452. * @usage = $this->mongo_db->offset($x);
  453. */
  454. public function offset($x = 0) {
  455. if ($x !== NULL && is_numeric($x) && $x >= 1) {
  456. $this->offset = (int) $x;
  457. } return($this);
  458. }
  459. /**
  460. *
  461. * GET_WHERE *
  462. *
  463. * Get the documents based upon the passed parameters *
  464. * @usage = $this->mongo_db->get_where('foo', array('bar' => 'something'));
  465. */
  466. public function get_where($collection = "", $where = array(), $limit = 99999, $orderby=array()) {
  467. if (is_array($orderby) || !emptyempty($orderby)) {
  468. $order_by = $this->order_by($order_by);
  469. }
  470. return($this->where($where)->limit($limit)->get($collection));
  471. }
  472. public function selectA($collection = "", $limit = 99999, $orderby=array()) {
  473. if(intval($limit)<1){
  474. $limit = 999999;
  475. }
  476. $order_by = $this->order_by($orderby);
  477. $re = $this->limit($limit)->get($collection);
  478. $this->clear();
  479. return (array)$re;
  480. }
  481. public function listinfo($collection = "", $orderby=array(), $page=1, $pagesize=12) {
  482. $page = max(intval($page), 1);
  483. $offset = $pagesize * ($page - 1);
  484. $pagesizes = $offset + $pagesize;
  485. $this->offset($offset);
  486. $order_by = $this->order_by($orderby);
  487. $re = $this->limit($pagesize)->get($collection);
  488. $this->limit(999999);
  489. $count = $this->count($collection);
  490. $this->pages = pages($count, $page, $pagesize);
  491. return (array)$re;
  492. }
  493. /**
  494. *
  495. * GET *
  496. *
  497. * Get the documents based upon the passed parameters *
  498. * @usage = $this->mongo_db->get('foo', array('bar' => 'something'));
  499. */
  500. public function get($collection = "") {
  501. if (emptyempty($collection)) {
  502. $this->error("In order to retreive documents from MongoDB, a collection name must be passed", 500);
  503. } $results = array();
  504. $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this->limit)->skip((int) $this->offset)->sort($this->sorts);
  505. $returns = array();
  506. foreach ($documents as $doc): $returns[] = $doc;
  507. endforeach;
  508. return($returns);
  509. }
  510. public function getMy($collection = "") {
  511. if (emptyempty($collection)) {
  512. $this->error("In order to retreive documents from MongoDB, a collection name must be passed", 500);
  513. } $results = array();
  514. $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this->limit)->skip((int) $this->offset)->sort($this->sorts);
  515. $returns = array();
  516. foreach ($documents as $doc): $returns[] = $doc;
  517. endforeach;
  518. $this -> clear();
  519. return($returns);
  520. }
  521. /**
  522. *
  523. * COUNT *
  524. *
  525. * Count the documents based upon the passed parameters *
  526. * @usage = $this->mongo_db->get('foo');
  527. */
  528. public function count($collection = "") {
  529. if (emptyempty($collection)) {
  530. $this->error("In order to retreive a count of documents from MongoDB, a collection name must be passed", 500);
  531. } $count = $this->db->{$collection}->find($this->wheres)->limit((int) $this->limit)->skip((int) $this->offset)->count();
  532. $this->clear();
  533. return($count);
  534. }
  535. /**
  536. *
  537. * INSERT *
  538. *
  539. * Insert a new document into the passed collection *
  540. * @usage = $this->mongo_db->insert('foo', $data = array());
  541. */
  542. public function insert($collection = "", $data = array(), $name='ID') {
  543. if (emptyempty($collection)) {
  544. $this->error("No Mongo collection selected to insert into", 500);
  545. } if (count($data) == 0 || !is_array($data)) {
  546. $this->error("Nothing to insert into Mongo collection or insert is not an array", 500);
  547. } try {
  548. /**
  549. wxcity_base::load_sys_class('whtysqs','',0);
  550. $mongoseq_class = new whtysqs('creaseidsqs');
  551. $re = $mongoseq_class->query("?name=" . $collection . "&opt=put&data=1");
  552. **/
  553. $re = put_sqs('list_mongo_creaseidsqs','1');
  554. if(is_numeric($re)){
  555. $re++;
  556. $data[$name] = intval($re);
  557. }else{
  558. $data[$name] = intval(time());
  559. //die('mongosqs error');
  560. }
  561. $this->db->{$collection}->insert($data, array('fsync' => TRUE));
  562. $this->clear();
  563. return $data[$name];
  564. } catch (MongoCursorException $e) {
  565. $this->error("Insert of data into MongoDB failed: {$e->getMessage()}", 500);
  566. }
  567. }
  568. public function insertWithId($collection = "", $data = array()) {
  569. if (emptyempty($collection)) {
  570. $this->error("No Mongo collection selected to insert into", 500);
  571. } if (count($data) == 0 || !is_array($data)) {
  572. $this->error("Nothing to insert into Mongo collection or insert is not an array", 500);
  573. } try {
  574. $this->db->{$collection}->insert($data, array('fsync' => TRUE));
  575. $this->clear();
  576. return 1;
  577. } catch (MongoCursorException $e) {
  578. $this->error("Insert of data into MongoDB failed: {$e->getMessage()}", 500);
  579. }
  580. }
  581. /**
  582. *
  583. * UPDATE *
  584. *
  585. * Update a document into the passed collection *
  586. * @usage = $this->mongo_db->update('foo', $data = array());
  587. */
  588. public function update($collection = "", $data = array()) {
  589. if (emptyempty($collection)) {
  590. $this->error("No Mongo collection selected to update", 500);
  591. } if (count($data) == 0 || !is_array($data)) {
  592. $this->error("Nothing to update in Mongo collection or update is not an array", 500);
  593. } try {
  594. $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => TRUE, 'multiple' => FALSE));
  595. $this->clear();
  596. return(TRUE);
  597. } catch (MongoCursorException $e) {
  598. $this->error("Update of data into MongoDB failed: {$e->getMessage()}", 500);
  599. }
  600. }
  601. /**
  602. *
  603. * UPDATE_ALL *
  604. *
  605. * Insert a new document into the passed collection *
  606. * @usage = $this->mongo_db->update_all('foo', $data = array());
  607. */
  608. public function update_all($collection = "", $data = array()) {
  609. if (emptyempty($collection)) {
  610. $this->error("No Mongo collection selected to update", 500);
  611. } if (count($data) == 0 || !is_array($data)) {
  612. $this->error("Nothing to update in Mongo collection or update is not an array", 500);
  613. } try {
  614. $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => TRUE, 'multiple' => TRUE));
  615. return(TRUE);
  616. } catch (MongoCursorException $e) {
  617. $this->error("Update of data into MongoDB failed: {$e->getMessage()}", 500);
  618. }
  619. }
  620. /**
  621. *
  622. * DELETE *
  623. *
  624. * delete document from the passed collection based upon certain criteria *
  625. * @usage = $this->mongo_db->delete('foo', $data = array());
  626. */
  627. public function delete($collection = "") {
  628. if (emptyempty($collection)) {
  629. $this->error("No Mongo collection selected to delete from", 500);
  630. } try {
  631. $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => TRUE));
  632. $this->clear();
  633. return(TRUE);
  634. } catch (MongoCursorException $e) {
  635. $this->error("Delete of data into MongoDB failed: {$e->getMessage()}", 500);
  636. }
  637. }
  638. /**
  639. *
  640. * DELETE_ALL *
  641. *
  642. * Delete all documents from the passed collection based upon certain criteria
  643. *
  644. * @usage = $this->mongo_db->delete_all('foo', $data = array());
  645. */
  646. public function delete_all($collection = "") {
  647. if (emptyempty($collection)) {
  648. $this->error("No Mongo collection selected to delete from", 500);
  649. } try {
  650. $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => FALSE));
  651. return(TRUE);
  652. } catch (MongoCursorException $e) {
  653. $this->error("Delete of data into MongoDB failed: {$e->getMessage()}", 500);
  654. }
  655. }
  656. /**
  657. *
  658. * ADD_INDEX *
  659. *
  660. * Ensure an index of the keys in a collection with optional parameters.
  661. To set values to descending order,
  662. * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be
  663. * set to 1 (ASC). *
  664. * @usage = $this->mongo_db->add_index($collection, array('first_name' => 'ASC', 'last_name' => -1), array('unique' => TRUE));
  665. */
  666. public function add_index($collection = "", $keys = array(), $options = array()) {
  667. if (emptyempty($collection)) {
  668. $this->error("No Mongo collection specified to add index to", 500);
  669. } if (emptyempty($keys) || !is_array($keys)) {
  670. $this->error("Index could not be created to MongoDB Collection because no keys were specified", 500);
  671. } foreach ($keys as $col => $val) {
  672. if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') {
  673. $keys[$col] = -1;
  674. } else {
  675. $keys[$col] = 1;
  676. }
  677. } if ($this->db->{$collection}->ensureIndex($keys, $options) == TRUE) {
  678. $this->clear();
  679. return($this);
  680. } else {
  681. $this->error("An error occured when trying to add an index to MongoDB Collection", 500);
  682. }
  683. }
  684. /**
  685. *
  686. * REMOVE_INDEX *
  687. *
  688. * Remove an index of the keys in a collection.
  689. To set values to descending order,
  690. * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be
  691. * set to 1 (ASC). *
  692. * @usage = $this->mongo_db->remove_index($collection, array('first_name' => 'ASC', 'last_name' => -1));
  693. */
  694. public function remove_index($collection = "", $keys = array()) {
  695. if (emptyempty($collection)) {
  696. $this->error("No Mongo collection specified to remove index from", 500);
  697. } if (emptyempty($keys) || !is_array($keys)) {
  698. $this->error("Index could not be removed from MongoDB Collection because no keys were specified", 500);
  699. } if ($this->db->{$collection}->deleteIndex($keys, $options) == TRUE) {
  700. $this->clear();
  701. return($this);
  702. } else {
  703. $this->error("An error occured when trying to remove an index from MongoDB Collection", 500);
  704. }
  705. }
  706. /**
  707. *
  708. * REMOVE_ALL_INDEXES *
  709. *
  710. * Remove all indexes from a collection. *
  711. * @usage = $this->mongo_db->remove_all_index($collection);
  712. */
  713. public function remove_all_indexes($collection = "") {
  714. if (emptyempty($collection)) {
  715. $this->error("No Mongo collection specified to remove all indexes from", 500);
  716. } $this->db->{$collection}->deleteIndexes();
  717. $this->clear();
  718. return($this);
  719. }
  720. /**
  721. *
  722. * LIST_INDEXES *
  723. *
  724. * Lists all indexes in a collection. *
  725. * @usage = $this->mongo_db->list_indexes($collection);
  726. */
  727. public function list_indexes($collection = "") {
  728. if (emptyempty($collection)) {
  729. $this->error("No Mongo collection specified to remove all indexes from", 500);
  730. } return($this->db->{$collection}->getIndexInfo());
  731. }
  732. /**
  733. *
  734. * DROP COLLECTION *
  735. *
  736. * Removes the specified collection from the database.
  737. Be careful because this
  738. * can have some very large issues in production!
  739. */
  740. public function drop_collection($collection = "") {
  741. if (emptyempty($collection)) {
  742. $this->error("No Mongo collection specified to drop from database", 500);
  743. } $this->db->{$collection}->drop();
  744. return TRUE;
  745. }
  746. /**
  747. *
  748. * CLEAR *
  749. *
  750. * Resets the class variables to default settings
  751. */
  752. private function clear() {
  753. $this->selects = array();
  754. $this->wheres = array();
  755. $this->limit = NULL;
  756. $this->offset = NULL;
  757. $this->sorts = array();
  758. }
  759. /**
  760. *
  761. * WHERE INITIALIZER *
  762. *
  763. * Prepares parameters for insertion in $wheres array().
  764. */
  765. private function where_init($param) {
  766. if (!isset($this->wheres[$param])) {
  767. $this->wheres[$param] = array();
  768. }
  769. }
  770. public function error($str, $t) {
  771. echo $str;
  772. exit;
  773. }
  774. }
  775. ?>

使用范例:

  1. $table_name=trim(strtolower($this->table_name));
  2. $this->mongo_db->where($where);
  3. $order=!emptyempty($order)?array('AID'=>'DESC'):array('AID'=>'ASC');
  4. //升序降序
  5. $infos=$this->mongo_db->listinfo($table_name,$order,$page,$pagesize);