搜索
首页后端开发php教程php封装的mongodb操作类

  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. class mongo_db {
  6. private $config;
  7. private $connection;
  8. private $db;
  9. private $connection_string;
  10. private $host;
  11. private $port;
  12. private $user;
  13. private $pass;
  14. private $dbname;
  15. private $persist;
  16. private $persist_key;
  17. private $selects = array();
  18. private $wheres = array();
  19. private $sorts = array();
  20. private $limit = 999999;
  21. private $offset = 0;
  22. private $timeout = 200;
  23. private $key = 0;
  24. /** * -------------------------------------------------------------------------------- * CONSTRUCTOR * -------------------------------------------------------------------------------- * * Automatically check if the Mongo PECL extension has been installed/enabled. * Generate the connection string and establish a connection to the MongoDB. */
  25. public function __construct() {
  26. if((IS_NOSQL != 1)){
  27. return;
  28. }
  29. if (!class_exists('Mongo')) {
  30. //$this->error("The MongoDB PECL extension has not been installed or enabled", 500);
  31. }
  32. $configs =wxcity_base::load_config("cache","mongo_db");
  33. $num = count($configs['connect']);
  34. $this->timeout = trim($configs['timeout']);
  35. $keys = wxcity_base::load_config('double');
  36. $this->key = $keys['mongo_db'];
  37. $this->config = $configs['connect'][$this->key];
  38. $status = $this->connect();
  39. if($status == false)
  40. {
  41. for($i = 1; $i {
  42. $n = $this->key + $i;
  43. $key = $n >= $num ? $n - $num : $n;
  44. $this->config = $configs['connect'][$key];
  45. $status = $this->connect();
  46. if($status!=false)
  47. {
  48. $keys['mongo_db'] = $key ;
  49. $this->key = $key;
  50. $data = "";
  51. file_put_contents(WHTY_PATH.'configs/double.php', $data, LOCK_EX);
  52. break;
  53. }
  54. }
  55. }
  56. if($status==false)
  57. {
  58. die('mongoDB not connect');
  59. }
  60. }
  61. function __destruct() {
  62. if((IS_NOSQL != 1)){
  63. return;
  64. }
  65. if($this->connection)
  66. {
  67. $this->connection->close();
  68. }
  69. }
  70. /** * -------------------------------------------------------------------------------- * CONNECT TO MONGODB * -------------------------------------------------------------------------------- * * Establish a connection to MongoDB using the connection string generated in * the connection_string() method. If 'mongo_persist_key' was set to true in the * config file, establish a persistent connection. We allow for only the 'persist' * option to be set because we want to establish a connection immediately. */
  71. private function connect() {
  72. $this->connection_string();
  73. $options = array('connect'=>true,'timeout'=>$this->timeout);
  74. try {
  75. $this->connection = new Mongo($this->connection_string, $options);
  76. $this->db = $this->connection->{$this->dbname};
  77. return($this);
  78. } catch (MongoConnectionException $e) {
  79. return false;
  80. }
  81. }
  82. /** * -------------------------------------------------------------------------------- * BUILD CONNECTION STRING * -------------------------------------------------------------------------------- * * Build the connection string from the config file. */
  83. private function connection_string() {
  84. $this->host = trim($this->config['hostname']);
  85. $this->port = trim($this->config['port']);
  86. $this->user = trim($this->config['username']);
  87. $this->pass = trim($this->config['password']);
  88. $this->dbname = trim($this->config['database']);
  89. $this->persist = trim($this->config['autoconnect']);
  90. $this->persist_key = trim($this->config['mongo_persist_key']);
  91. $connection_string = "mongodb://";
  92. if (emptyempty($this->host)) {
  93. $this->error("The Host must be set to connect to MongoDB", 500);
  94. } if (emptyempty($this->dbname)) {
  95. $this->error("The Database must be set to connect to MongoDB", 500);
  96. } if (!emptyempty($this->user) && !emptyempty($this->pass)) {
  97. $connection_string .= "{$this->user}:{$this->pass}@";
  98. } if (isset($this->port) && !emptyempty($this->port)) {
  99. $connection_string .= "{$this->host}:{$this->port}";
  100. } else {
  101. $connection_string .= "{$this->host}";
  102. } $this->connection_string = trim($connection_string);
  103. }
  104. /** * -------------------------------------------------------------------------------- * Switch_db * -------------------------------------------------------------------------------- * * Switch from default database to a different db */
  105. public function switch_db($database = '') {
  106. if (emptyempty($database)) {
  107. $this->error("To switch MongoDB databases, a new database name must be specified", 500);
  108. } $this->dbname = $database;
  109. try {
  110. $this->db = $this->connection->{$this->dbname};
  111. return(TRUE);
  112. } catch (Exception $e) {
  113. $this->error("Unable to switch Mongo Databases: {$e->getMessage()}", 500);
  114. }
  115. }
  116. /** * -------------------------------------------------------------------------------- * SELECT FIELDS * -------------------------------------------------------------------------------- * * Determine which fields to include OR which to exclude during the query process. * Currently, including and excluding at the same time is not available, so the * $includes array will take precedence over the $excludes array. If you want to * only choose fields to exclude, leave $includes an empty array(). * * @usage: $this->mongo_db->select(array('foo', 'bar'))->get('foobar'); */
  117. public function select($includes = array(), $excludes = array()) {
  118. if (!is_array($includes)) {
  119. $includes = array();
  120. }
  121. if (!is_array($excludes)) {
  122. $excludes = array();
  123. }
  124. if (!emptyempty($includes)) {
  125. foreach ($includes as $col) {
  126. $this->selects[$col] = 1;
  127. }
  128. } else {
  129. foreach ($excludes as $col) {
  130. $this->selects[$col] = 0;
  131. }
  132. } return($this);
  133. }
  134. /** * -------------------------------------------------------------------------------- * WHERE PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents based on these search parameters. The $wheres array should * be an associative array with the field as the key and the value as the search * criteria. * * @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar'); */
  135. public function where($wheres = array()) {
  136. foreach ((array)$wheres as $wh => $val) {
  137. $this->wheres[$wh] = $val;
  138. } return($this);
  139. }
  140. /** * -------------------------------------------------------------------------------- * WHERE_IN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is in a given $in array(). * * @usage = $this->mongo_db->where_in('foo', array('bar', 'zoo', 'blah'))->get('foobar'); */
  141. public function where_in($field = "", $in = array()) {
  142. $this->where_init($field);
  143. $this->wheres[$field]['$in'] = $in;
  144. return($this);
  145. }
  146. /** * -------------------------------------------------------------------------------- * WHERE_NOT_IN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is not in a given $in array(). * * @usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo', 'blah'))->get('foobar'); */
  147. public function where_not_in($field = "", $in = array()) {
  148. $this->where_init($field);
  149. $this->wheres[$field]['$nin'] = $in;
  150. return($this);
  151. }
  152. /** * -------------------------------------------------------------------------------- * WHERE GREATER THAN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is greater than $x * * @usage = $this->mongo_db->where_gt('foo', 20); */
  153. public function where_gt($field = "", $x) {
  154. $this->where_init($field);
  155. $this->wheres[$field]['$gt'] = $x;
  156. return($this);
  157. }
  158. /** * -------------------------------------------------------------------------------- * WHERE GREATER THAN OR EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is greater than or equal to $x * * @usage = $this->mongo_db->where_gte('foo', 20); */
  159. public function where_gte($field = "", $x) {
  160. $this->where_init($field);
  161. $this->wheres[$field]['$gte'] = $x;
  162. return($this);
  163. }
  164. /** * -------------------------------------------------------------------------------- * WHERE LESS THAN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is less than $x * * @usage = $this->mongo_db->where_lt('foo', 20); */
  165. public function where_lt($field = "", $x) {
  166. $this->where_init($field);
  167. $this->wheres[$field]['$lt'] = $x;
  168. return($this);
  169. }
  170. /** * -------------------------------------------------------------------------------- * WHERE LESS THAN OR EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is less than or equal to $x * * @usage = $this->mongo_db->where_lte('foo', 20); */
  171. public function where_lte($field = "", $x) {
  172. $this->where_init($field);
  173. $this->wheres[$field]['$lte'] = $x;
  174. return($this);
  175. }
  176. /** * -------------------------------------------------------------------------------- * WHERE BETWEEN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is between $x and $y * * @usage = $this->mongo_db->where_between('foo', 20, 30); */
  177. public function where_between($field = "", $x, $y) {
  178. $this->where_init($field);
  179. $this->wheres[$field]['$gte'] = $x;
  180. $this->wheres[$field]['$lte'] = $y;
  181. return($this);
  182. }
  183. /** * -------------------------------------------------------------------------------- * WHERE BETWEEN AND NOT EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is between but not equal to $x and $y * * @usage = $this->mongo_db->where_between_ne('foo', 20, 30); */
  184. public function where_between_ne($field = "", $x, $y) {
  185. $this->where_init($field);
  186. $this->wheres[$field]['$gt'] = $x;
  187. $this->wheres[$field]['$lt'] = $y;
  188. return($this);
  189. }
  190. /** * -------------------------------------------------------------------------------- * WHERE NOT EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is not equal to $x * * @usage = $this->mongo_db->where_between('foo', 20, 30); */
  191. public function where_ne($field = "", $x) {
  192. $this->where_init($field);
  193. $this->wheres[$field]['$ne'] = $x;
  194. return($this);
  195. }
  196. /** * -------------------------------------------------------------------------------- * WHERE OR * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is in one or more values * * @usage = $this->mongo_db->where_or('foo', array( 'foo', 'bar', 'blegh' ); */
  197. public function where_or($field = "", $values) {
  198. $this->where_init($field);
  199. $this->wheres[$field]['$or'] = $values;
  200. return($this);
  201. }
  202. /** * -------------------------------------------------------------------------------- * WHERE AND * -------------------------------------------------------------------------------- * * Get the documents where the elements match the specified values * * @usage = $this->mongo_db->where_and( array ( 'foo' => 1, 'b' => 'someexample' ); */
  203. public function where_and($elements_values = array()) {
  204. foreach ((array)$elements_values as $element => $val) {
  205. $this->wheres[$element] = $val;
  206. } return($this);
  207. }
  208. /** * -------------------------------------------------------------------------------- * WHERE MOD * -------------------------------------------------------------------------------- * * Get the documents where $field % $mod = $result * * @usage = $this->mongo_db->where_mod( 'foo', 10, 1 ); */
  209. public function where_mod($field, $num, $result) {
  210. $this->where_init($field);
  211. $this->wheres[$field]['$mod'] = array($num, $result);
  212. return($this);
  213. }
  214. /** * -------------------------------------------------------------------------------- * 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'); */
  215. public function where_size($field = "", $size = "") {
  216. $this->_where_init($field);
  217. $this->wheres[$field]['$size'] = $size;
  218. return ($this);
  219. }
  220. /** * -------------------------------------------------------------------------------- * LIKE PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the (string) value of a $field is like a value. The defaults * allow for a case-insensitive search. * * @param $flags * Allows for the typical regular expression flags: * i = case insensitive * m = multiline * x = can contain comments * l = locale * s = dotall, "." matches everything, including newlines * u = match unicode * * @param $enable_start_wildcard * If set to anything other than TRUE, a starting line character "^" will be prepended * to the search value, representing only searching for a value at the start of * a new line. * * @param $enable_end_wildcard * If set to anything other than TRUE, an ending line character "$" will be appended * to the search value, representing only searching for a value at the end of * a line. * * @usage = $this->mongo_db->like('foo', 'bar', 'im', FALSE, TRUE); */
  221. public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = TRUE, $enable_end_wildcard = TRUE) {
  222. $field = (string) trim($field);
  223. $this->where_init($field);
  224. $value = (string) trim($value);
  225. $value = quotemeta($value);
  226. if ($enable_start_wildcard !== TRUE) {
  227. $value = "^" . $value;
  228. } if ($enable_end_wildcard !== TRUE) {
  229. $value .= "$";
  230. } $regex = "/$value/$flags";
  231. $this->wheres[$field] = new MongoRegex($regex);
  232. return($this);
  233. }
  234. public function wheres($where){
  235. $this->wheres = $where;
  236. }
  237. /** * -------------------------------------------------------------------------------- * ORDER BY PARAMETERS * -------------------------------------------------------------------------------- * * Sort the documents based on the parameters passed. To set values to descending order, * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be * set to 1 (ASC). * * @usage = $this->mongo_db->where_between('foo', 20, 30); */
  238. public function order_by($fields = array()) {
  239. if (!is_array($fields) || !count($fields)) return ;
  240. foreach ($fields as $col => $val) {
  241. if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') {
  242. $this->sorts[$col] = -1;
  243. } else {
  244. $this->sorts[$col] = 1;
  245. }
  246. } return($this);
  247. }
  248. /** * -------------------------------------------------------------------------------- * LIMIT DOCUMENTS * -------------------------------------------------------------------------------- * * Limit the result set to $x number of documents * * @usage = $this->mongo_db->limit($x); */
  249. public function limit($x = 99999) {
  250. if ($x !== NULL && is_numeric($x) && $x >= 1) {
  251. $this->limit = (int) $x;
  252. } return($this);
  253. }
  254. /** * -------------------------------------------------------------------------------- * OFFSET DOCUMENTS * -------------------------------------------------------------------------------- * * Offset the result set to skip $x number of documents * * @usage = $this->mongo_db->offset($x); */
  255. public function offset($x = 0) {
  256. if ($x !== NULL && is_numeric($x) && $x >= 1) {
  257. $this->offset = (int) $x;
  258. } return($this);
  259. }
  260. /** * -------------------------------------------------------------------------------- * GET_WHERE * -------------------------------------------------------------------------------- * * Get the documents based upon the passed parameters * * @usage = $this->mongo_db->get_where('foo', array('bar' => 'something')); */
  261. public function get_where($collection = "", $where = array(), $limit = 99999, $orderby=array()) {
  262. if (is_array($orderby) || !emptyempty($orderby)) {
  263. $order_by = $this->order_by($order_by);
  264. }
  265. return($this->where($where)->limit($limit)->get($collection));
  266. }
  267. public function selectA($collection = "", $limit = 99999, $orderby=array()) {
  268. if(intval($limit) $limit = 999999;
  269. }
  270. $order_by = $this->order_by($orderby);
  271. $re = $this->limit($limit)->get($collection);
  272. $this->clear();
  273. return (array)$re;
  274. }
  275. public function listinfo($collection = "", $orderby=array(), $page=1, $pagesize=12) {
  276. $page = max(intval($page), 1);
  277. $offset = $pagesize * ($page - 1);
  278. $pagesizes = $offset + $pagesize;
  279. $this->offset($offset);
  280. $order_by = $this->order_by($orderby);
  281. $re = $this->limit($pagesize)->get($collection);
  282. $this->limit(999999);
  283. $count = $this->count($collection);
  284. $this->pages = pages($count, $page, $pagesize);
  285. return (array)$re;
  286. }
  287. /** * -------------------------------------------------------------------------------- * GET * -------------------------------------------------------------------------------- * * Get the documents based upon the passed parameters * * @usage = $this->mongo_db->get('foo', array('bar' => 'something')); */
  288. public function get($collection = "") {
  289. if (emptyempty($collection)) {
  290. $this->error("In order to retreive documents from MongoDB, a collection name must be passed", 500);
  291. } $results = array();
  292. $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this->limit)->skip((int) $this->offset)->sort($this->sorts);
  293. $returns = array();
  294. foreach ($documents as $doc): $returns[] = $doc;
  295. endforeach;
  296. return($returns);
  297. }
  298. public function getMy($collection = "") {
  299. if (emptyempty($collection)) {
  300. $this->error("In order to retreive documents from MongoDB, a collection name must be passed", 500);
  301. } $results = array();
  302. $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this->limit)->skip((int) $this->offset)->sort($this->sorts);
  303. $returns = array();
  304. foreach ($documents as $doc): $returns[] = $doc;
  305. endforeach;
  306. $this -> clear();
  307. return($returns);
  308. }
  309. /** * -------------------------------------------------------------------------------- * COUNT * -------------------------------------------------------------------------------- * * Count the documents based upon the passed parameters * * @usage = $this->mongo_db->get('foo'); */
  310. public function count($collection = "") {
  311. if (emptyempty($collection)) {
  312. $this->error("In order to retreive a count of documents from MongoDB, a collection name must be passed", 500);
  313. } $count = $this->db->{$collection}->find($this->wheres)->limit((int) $this->limit)->skip((int) $this->offset)->count();
  314. $this->clear();
  315. return($count);
  316. }
  317. /** * -------------------------------------------------------------------------------- * INSERT * -------------------------------------------------------------------------------- * * Insert a new document into the passed collection * * @usage = $this->mongo_db->insert('foo', $data = array()); */
  318. public function insert($collection = "", $data = array(), $name='ID') {
  319. if (emptyempty($collection)) {
  320. $this->error("No Mongo collection selected to insert into", 500);
  321. } if (count($data) == 0 || !is_array($data)) {
  322. $this->error("Nothing to insert into Mongo collection or insert is not an array", 500);
  323. } try {
  324. /**
  325. wxcity_base::load_sys_class('whtysqs','',0);
  326. $mongoseq_class = new whtysqs('creaseidsqs');
  327. $re = $mongoseq_class->query("?name=" . $collection . "&opt=put&data=1");
  328. **/
  329. $re = put_sqs('list_mongo_creaseidsqs','1');
  330. if(is_numeric($re)){
  331. $re++;
  332. $data[$name] = intval($re);
  333. }else{
  334. $data[$name] = intval(time());
  335. //die('mongosqs error');
  336. }
  337. $this->db->{$collection}->insert($data, array('fsync' => TRUE));
  338. $this->clear();
  339. return $data[$name];
  340. } catch (MongoCursorException $e) {
  341. $this->error("Insert of data into MongoDB failed: {$e->getMessage()}", 500);
  342. }
  343. }
  344. public function insertWithId($collection = "", $data = array()) {
  345. if (emptyempty($collection)) {
  346. $this->error("No Mongo collection selected to insert into", 500);
  347. } if (count($data) == 0 || !is_array($data)) {
  348. $this->error("Nothing to insert into Mongo collection or insert is not an array", 500);
  349. } try {
  350. $this->db->{$collection}->insert($data, array('fsync' => TRUE));
  351. $this->clear();
  352. return 1;
  353. } catch (MongoCursorException $e) {
  354. $this->error("Insert of data into MongoDB failed: {$e->getMessage()}", 500);
  355. }
  356. }
  357. /** * -------------------------------------------------------------------------------- * UPDATE * -------------------------------------------------------------------------------- * * Update a document into the passed collection * * @usage = $this->mongo_db->update('foo', $data = array()); */
  358. public function update($collection = "", $data = array()) {
  359. if (emptyempty($collection)) {
  360. $this->error("No Mongo collection selected to update", 500);
  361. } if (count($data) == 0 || !is_array($data)) {
  362. $this->error("Nothing to update in Mongo collection or update is not an array", 500);
  363. } try {
  364. $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => TRUE, 'multiple' => FALSE));
  365. $this->clear();
  366. return(TRUE);
  367. } catch (MongoCursorException $e) {
  368. $this->error("Update of data into MongoDB failed: {$e->getMessage()}", 500);
  369. }
  370. }
  371. /** * -------------------------------------------------------------------------------- * UPDATE_ALL * -------------------------------------------------------------------------------- * * Insert a new document into the passed collection * * @usage = $this->mongo_db->update_all('foo', $data = array()); */
  372. public function update_all($collection = "", $data = array()) {
  373. if (emptyempty($collection)) {
  374. $this->error("No Mongo collection selected to update", 500);
  375. } if (count($data) == 0 || !is_array($data)) {
  376. $this->error("Nothing to update in Mongo collection or update is not an array", 500);
  377. } try {
  378. $this->db->{$collection}->update($this->wheres, array('$set' => $data), array('fsync' => TRUE, 'multiple' => TRUE));
  379. return(TRUE);
  380. } catch (MongoCursorException $e) {
  381. $this->error("Update of data into MongoDB failed: {$e->getMessage()}", 500);
  382. }
  383. }
  384. /** * -------------------------------------------------------------------------------- * DELETE * -------------------------------------------------------------------------------- * * delete document from the passed collection based upon certain criteria * * @usage = $this->mongo_db->delete('foo', $data = array()); */
  385. public function delete($collection = "") {
  386. if (emptyempty($collection)) {
  387. $this->error("No Mongo collection selected to delete from", 500);
  388. } try {
  389. $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => TRUE));
  390. $this->clear();
  391. return(TRUE);
  392. } catch (MongoCursorException $e) {
  393. $this->error("Delete of data into MongoDB failed: {$e->getMessage()}", 500);
  394. }
  395. }
  396. /** * -------------------------------------------------------------------------------- * DELETE_ALL * -------------------------------------------------------------------------------- * * Delete all documents from the passed collection based upon certain criteria * * @usage = $this->mongo_db->delete_all('foo', $data = array()); */
  397. public function delete_all($collection = "") {
  398. if (emptyempty($collection)) {
  399. $this->error("No Mongo collection selected to delete from", 500);
  400. } try {
  401. $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => FALSE));
  402. return(TRUE);
  403. } catch (MongoCursorException $e) {
  404. $this->error("Delete of data into MongoDB failed: {$e->getMessage()}", 500);
  405. }
  406. }
  407. /** * -------------------------------------------------------------------------------- * ADD_INDEX * -------------------------------------------------------------------------------- * * Ensure an index of the keys in a collection with optional parameters. To set values to descending order, * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be * set to 1 (ASC). * * @usage = $this->mongo_db->add_index($collection, array('first_name' => 'ASC', 'last_name' => -1), array('unique' => TRUE)); */
  408. public function add_index($collection = "", $keys = array(), $options = array()) {
  409. if (emptyempty($collection)) {
  410. $this->error("No Mongo collection specified to add index to", 500);
  411. } if (emptyempty($keys) || !is_array($keys)) {
  412. $this->error("Index could not be created to MongoDB Collection because no keys were specified", 500);
  413. } foreach ($keys as $col => $val) {
  414. if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') {
  415. $keys[$col] = -1;
  416. } else {
  417. $keys[$col] = 1;
  418. }
  419. } if ($this->db->{$collection}->ensureIndex($keys, $options) == TRUE) {
  420. $this->clear();
  421. return($this);
  422. } else {
  423. $this->error("An error occured when trying to add an index to MongoDB Collection", 500);
  424. }
  425. }
  426. /** * -------------------------------------------------------------------------------- * REMOVE_INDEX * -------------------------------------------------------------------------------- * * Remove an index of the keys in a collection. To set values to descending order, * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be * set to 1 (ASC). * * @usage = $this->mongo_db->remove_index($collection, array('first_name' => 'ASC', 'last_name' => -1)); */
  427. public function remove_index($collection = "", $keys = array()) {
  428. if (emptyempty($collection)) {
  429. $this->error("No Mongo collection specified to remove index from", 500);
  430. } if (emptyempty($keys) || !is_array($keys)) {
  431. $this->error("Index could not be removed from MongoDB Collection because no keys were specified", 500);
  432. } if ($this->db->{$collection}->deleteIndex($keys, $options) == TRUE) {
  433. $this->clear();
  434. return($this);
  435. } else {
  436. $this->error("An error occured when trying to remove an index from MongoDB Collection", 500);
  437. }
  438. }
  439. /** * -------------------------------------------------------------------------------- * REMOVE_ALL_INDEXES * -------------------------------------------------------------------------------- * * Remove all indexes from a collection. * * @usage = $this->mongo_db->remove_all_index($collection); */
  440. public function remove_all_indexes($collection = "") {
  441. if (emptyempty($collection)) {
  442. $this->error("No Mongo collection specified to remove all indexes from", 500);
  443. } $this->db->{$collection}->deleteIndexes();
  444. $this->clear();
  445. return($this);
  446. }
  447. /** * -------------------------------------------------------------------------------- * LIST_INDEXES * -------------------------------------------------------------------------------- * * Lists all indexes in a collection. * * @usage = $this->mongo_db->list_indexes($collection); */
  448. public function list_indexes($collection = "") {
  449. if (emptyempty($collection)) {
  450. $this->error("No Mongo collection specified to remove all indexes from", 500);
  451. } return($this->db->{$collection}->getIndexInfo());
  452. }
  453. /** * -------------------------------------------------------------------------------- * DROP COLLECTION * -------------------------------------------------------------------------------- * * Removes the specified collection from the database. Be careful because this * can have some very large issues in production! */
  454. public function drop_collection($collection = "") {
  455. if (emptyempty($collection)) {
  456. $this->error("No Mongo collection specified to drop from database", 500);
  457. } $this->db->{$collection}->drop();
  458. return TRUE;
  459. }
  460. /** * -------------------------------------------------------------------------------- * CLEAR * -------------------------------------------------------------------------------- * * Resets the class variables to default settings */
  461. private function clear() {
  462. $this->selects = array();
  463. $this->wheres = array();
  464. $this->limit = NULL;
  465. $this->offset = NULL;
  466. $this->sorts = array();
  467. }
  468. /** * -------------------------------------------------------------------------------- * WHERE INITIALIZER * -------------------------------------------------------------------------------- * * Prepares parameters for insertion in $wheres array(). */
  469. private function where_init($param) {
  470. if (!isset($this->wheres[$param])) {
  471. $this->wheres[$param] = array();
  472. }
  473. }
  474. public function error($str, $t) {
  475. echo $str;
  476. exit;
  477. }
  478. }
  479. ?>
复制代码

使用范例
  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. $infos=$this->mongo_db->listinfo($table_name,$order,$page,$pagesize);
复制代码

php, mongodb


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何防止与会议有关的跨站点脚本(XSS)攻击?您如何防止与会议有关的跨站点脚本(XSS)攻击?Apr 23, 2025 am 12:16 AM

要保护应用免受与会话相关的XSS攻击,需采取以下措施:1.设置HttpOnly和Secure标志保护会话cookie。2.对所有用户输入进行输出编码。3.实施内容安全策略(CSP)限制脚本来源。通过这些策略,可以有效防护会话相关的XSS攻击,确保用户数据安全。

您如何优化PHP会话性能?您如何优化PHP会话性能?Apr 23, 2025 am 12:13 AM

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显着提升应用在高并发环境下的效率。

什么是session.gc_maxlifetime配置设置?什么是session.gc_maxlifetime配置设置?Apr 23, 2025 am 12:10 AM

thesession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceIsiseededeedeedeedeedeedeedto to to avoidperformance andununununununexpectedLogOgouts.3)

您如何在PHP中配置会话名?您如何在PHP中配置会话名?Apr 23, 2025 am 12:08 AM

在PHP中,可以使用session_name()函数配置会话名称。具体步骤如下:1.使用session_name()函数设置会话名称,例如session_name("my_session")。2.在设置会话名称后,调用session_start()启动会话。配置会话名称可以避免多应用间的会话数据冲突,并增强安全性,但需注意会话名称的唯一性、安全性、长度和设置时机。

您应该多久再生一次会话ID?您应该多久再生一次会话ID?Apr 23, 2025 am 12:03 AM

会话ID应在登录时、敏感操作前和每30分钟定期重新生成。1.登录时重新生成会话ID可防会话固定攻击。2.敏感操作前重新生成提高安全性。3.定期重新生成降低长期利用风险,但需权衡用户体验。

如何在PHP中设置会话cookie参数?如何在PHP中设置会话cookie参数?Apr 22, 2025 pm 05:33 PM

在PHP中设置会话cookie参数可以通过session_set_cookie_params()函数实现。1)使用该函数设置参数,如过期时间、路径、域名、安全标志等;2)调用session_start()使参数生效;3)根据需求动态调整参数,如用户登录状态;4)注意设置secure和httponly标志以提升安全性。

在PHP中使用会议的主要目的是什么?在PHP中使用会议的主要目的是什么?Apr 22, 2025 pm 05:25 PM

在PHP中使用会话的主要目的是维护用户在不同页面之间的状态。1)会话通过session_start()函数启动,创建唯一会话ID并存储在用户cookie中。2)会话数据保存在服务器上,允许在不同请求间传递数据,如登录状态和购物车内容。

您如何在子域中分享会议?您如何在子域中分享会议?Apr 22, 2025 pm 05:21 PM

如何在子域名间共享会话?通过设置通用域名的会话cookie实现。1.在服务器端设置会话cookie的域为.example.com。2.选择合适的会话存储方式,如内存、数据库或分布式缓存。3.通过cookie传递会话ID,服务器根据ID检索和更新会话数据。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版