首页 > 开发 > PHP > 正文

php操作MongoDB类实例

2024-05-04 23:36:19
字体:大 中 小
来源:转载
供稿:网友

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

希望本文所述对大家的php程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表