IspMongo.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2019/5/8 0008
  6. * Time: 14:38
  7. */
  8. class IspMongo
  9. {
  10. static private $mongo_obj = null;
  11. /**
  12. * 查询mongo
  13. * @param $table_name
  14. * @param array $params
  15. * @param array $other_pra
  16. * @return array
  17. */
  18. static public function selectMongo($table_name,$params = array(),$other_pra = array()){
  19. $res = array();
  20. $mongo = Yii::app()->params['mongodb'];
  21. $mongo_server = $mongo['server'];
  22. $mongo_db = $mongo['db'];
  23. try {
  24. // if(class_exists('MongoClient')){
  25. // self::$mongo_obj = new MongoClient($mongo_server);
  26. // }else{
  27. // }
  28. self::$mongo_obj = new Mongo($mongo_server);
  29. $collection=self::$mongo_obj->selectCollection($mongo_db,$table_name);
  30. if (isset($other_pra['fields']) && $other_pra['fields']) {
  31. $fields = $other_pra['fields'];
  32. }else{
  33. $fields = array();
  34. }
  35. if (isset($other_pra['sort']) && $other_pra['sort']) {
  36. $sort = $other_pra['sort'];
  37. }else{
  38. $sort = array();
  39. }
  40. if (isset($other_pra['limit']) && $other_pra['limit']) {
  41. $limit = $other_pra['limit'];
  42. }else{
  43. $limit = array();
  44. }
  45. //返回数据是否重建索引
  46. if (isset($other_pra['is_index'])) {
  47. $is_index = $other_pra['is_index'];
  48. }else{
  49. $is_index = true;
  50. }
  51. $cursor = $collection->find($params,$fields);
  52. if($sort){
  53. $cursor->sort($sort);
  54. }
  55. if($limit){
  56. $cursor->limit($limit);
  57. }
  58. if($cursor){
  59. $res = iterator_to_array($cursor);
  60. }
  61. self::close();
  62. if($res && is_array($res)){
  63. if ($is_index) {
  64. $_res = $res;
  65. $res = array();
  66. foreach ($_res as $re) {
  67. $res[$re['_id']] = $re;
  68. }
  69. }
  70. unset($_res);
  71. }
  72. } catch (Exception $ex) {
  73. exit($ex->getMessage());
  74. }
  75. return $res;
  76. }
  77. static public function close()
  78. {
  79. if (self::$mongo_obj) {
  80. self::$mongo_obj->close();
  81. }
  82. }
  83. }