搜尋
首頁後端開發php教程php封裝的mongodb操作類

  1. /*
  2. * 이 템플릿을 변경하려면 도구 | 템플릿
  3. * 편집기에서 템플릿을 엽니다.
  4. */
  5. class mongo_db {
  6. private $config;
  7. 비공개 $connection;
  8. 비공개 $db;
  9. 비공개 $connection_string;
  10. 비공개 $host;
  11. 비공개 $port;
  12. 개인 $user;
  13. 비공개 $pass;
  14. 비공개 $dbname;
  15. 비공개 $persist;
  16. 비공개 $persist_key;
  17. 비공개 $selects = array();
  18. 비공개 $wheres = array();
  19. 비공개 $sorts = array();
  20. 비공개 $limit = 999999;
  21. 비공개 $offset = 0;
  22. 비공개 $timeout = 200;
  23. 개인 $key = 0;
  24. /*** ------------------------------------------------- ------------------ * 생성자 * --- ------------------------------------- -------------- * * Mongo PECL 확장이 설치/활성화되었는지 자동으로 확인합니다. * 연결 문자열을 생성하고 MongoDB에 대한 연결을 설정합니다.*/
  25. 공개 함수 __construct() {
  26. if((IS_NOSQL != 1)){
  27. return;
  28. }
  29. if (!class_exists('Mongo')) {
  30. //$this->error("MongoDB PECL 확장이 설치되지 않았거나 활성화되지 않았습니다.", 500);
  31. }
  32. $configs =wxcity_base::load_config("캐시","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-> 키 $i;
  43. $key = $n >= $num ? $n - $번호 : $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. 휴식;
  53. }
  54. }
  55. }
  56. if($status==false)
  57. {
  58. die('mongoDB가 연결되지 않음');
  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. /*** ------------------------------------------------- ------------------ * MONGODB에 연결 * -------------- ------------------------------------- ---------------- * * * Connection_string() 메소드에서 생성된 연결 문자열을 사용하여 MongoDB에 대한 연결을 설정합니다. * 구성 파일에서 'mongo_persist_key'가 true로 설정된 경우 영구 연결을 설정합니다. 즉시 연결을 설정하려고 하기 때문에 'persist' * 옵션만 설정하도록 허용합니다.*/
  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. /*** ------------------------------------------------- ------------------ * 연결 문자열 빌드 * -------------- ------------------------------------- ---------------- * * 구성 파일에서 연결 문자열을 작성합니다.*/
  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("MongoDB에 연결하려면 호스트를 설정해야 합니다.", 500);
  94. } if (emptyempty($this->dbname)) {
  95. $this->error("MongoDB에 연결하려면 데이터베이스를 설정해야 합니다.", 500);
  96. } if (!emptyempty($this->user) && !emptyempty($this->pass)) {
  97. $connection_string .= "{$this->user}:{$this- >통과}@";
  98. } if (isset($this->port) && !emptyempty($this->port)) {
  99. $connection_string .= "{$this->host}:{$this-> ;포트}";
  100. } else {
  101. $connection_string .= "{$this->host}";
  102. } $this->connection_string = 트림($connection_string);
  103. }
  104. /*** ------------------------------------------------- ------------------ * Switch_db * --- ------------------------------------- -------------- * * 기본 데이터베이스에서 다른 데이터베이스로 전환*/
  105. public function switch_db($database = '') {
  106. if (emptyempty($database)) {
  107. $this- >error("MongoDB 데이터베이스를 전환하려면 새 데이터베이스 이름을 지정해야 합니다.", 500);
  108. } $this->dbname = $database;
  109. try {
  110. $this->db = $this->connection->{$this->dbname};
  111. 반환(TRUE);
  112. } catch (Exception $e) {
  113. $this->error("Mongo 데이터베이스를 전환할 수 없습니다: {$e->getMessage()}", 500);
  114. }
  115. }
  116. /*** ------------------------------------------------- ------------------ * 필드 선택 * --------------- ------------------------------------- --------------- * * 쿼리 프로세스 중에 포함할 필드 또는 제외할 필드를 결정합니다. * 현재는 포함과 제외를 동시에 수행할 수 없으므로 * $includes 배열이 $excludes 배열보다 우선합니다. * 제외할 필드만 선택하려면 $includes에 빈 배열()을 남겨 두십시오. * * @usage: $this->mongo_db->select(array('foo', 'bar'))->get('foobar');*/
  117. 공용 함수 select($includes = array(), $excludes = array()) {
  118. if (! is_array($includes)) {
  119. $includes = 배열();
  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. /*** ------------------------------------------------- ------------------ * 매개변수의 위치 * --------------- ------------------------------------- --------------- * * 이러한 검색 매개변수를 기반으로 문서를 가져옵니다. $wheres 배열은 필드를 키로, 값을 검색 기준으로 * 연관 배열이어야 합니다. * * @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar');*/
  135. 공용 함수 where($wheres = array()) {
  136. foreach ((array)$wheres as $wh => $ val) {
  137. $this->wheres[$wh] = $val;
  138. } return($this);
  139. }
  140. /*** ------------------------------------------------- ------------------------------- * WHERE_IN 參數 * --------------- -------------------------------------------------- --------------- * * 取得給定$in array() 中$field 的值所在的文件。 * * @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. 返回($this);
  145. }
  146. /*** ------------------------------------------------- ------------------------------- * WHERE_NOT_IN 參數 * --------------- --- ----------------------------------------------- --- --------------- * * 取得$field 的值不在給定$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($現場);
  149. $this->wheres[$field]['$nin'] = $in;
  150. 回傳($this); }
  151. /*** ------------------------------------------------- ------------------------------- * 大於參數 * ------------- -- ------------------------------------------------ -- --------------- * * 取得$field的值大於$x的文檔* * @usage = $this->mongo_db->where_gt( '富', 20);* /
  152. public function where_gt($field = "", $x) {
  153. $this->where_init($field);
  154. $this->wheres[$field]['$gt'] = $x;
  155. 回傳($this)
  156. }
  157. /*** ------------------------------------------------- ------------------------------- * 大於或等於參數 * ---------- --- ----------------------------------------------- --- ----------------- * * 取得$field的值大於等於$x的文件* * @usage = $this-> mongo_db->where_gte('foo', 20) ;*/
  158. public function where_gte($field = "", $x) {
  159. $this-> where_init($field);
  160. $this->wheres[$field]['$gte'] = $x;
  161. 回傳($this)
  162. }
  163. /*** ------------------------------------------------- ------------------------------- * 小於參數的地方 * ------------- -------------------------------------------------- ----------------- * * 取得$field的值小於$x的文檔* * @usage = $this->mongo_db->where_lt( '富', 20);*/
  164. public function where_lt($field = "", $x) {
  165. $this->where_init($field);
  166. $this->wheres[$field ]['$lt '] = $x;
  167. 回傳($this) }
  168. /*** ------------------------------------------------- ------------------------------- * 小於或等於參數 * ---------- --- ----------------------------------------------- --- ----------------- * * 取得$field的值小於或等於$x的文檔* * @usage = $this-> mongo_db->where_lte('foo', 20 );*/
  169. public function where_lte($field = "" , $x) {
  170. $ this->where_init($field)
  171. $this->wheres[$field]['$lte'] = $x;
  172. 回傳($this); 🎜> }
  173. /* ** ------------------------------------------------- ------------------------------- * 參數之間的位置* ------------ -- ------------------------------------------------ -- ---------------- * * 取得$field的值在$x和$y之間的文件* * @usage = $this->mongo_db->where_ Between ( 'foo', 20, 30);*/
  174. public function where_ Between($field = "", $x, $y) {
  175. $this->where_init($field ) ;
  176. $this->wheres[$ field]['$gte'] = $x;
  177. $this->wheres[$field]['$lte'] = $y;
  178. 回傳( $這個);
  179. }
  180. /*** ------------------------------------------------- ------------------ * 매개변수 사이 및 매개변수와 같지 않음 * ---------- ------------------------------------- ------- * * $field의 값이 $x와 $y 사이이지만 같지 않은 문서를 가져옵니다. * * @usage = $this ->mongo_db->where_between_ne('foo', 20, 30);*/
  181. 공개 함수 where_between_ne($field = "", $x, $y) {
  182. $this->where_init($field);
  183. $this->wheres[$field]['$gt'] = $x;
  184. $this->wheres[$field]['$lt'] = $y;
  185. return($this);
  186. }
  187. /*** ------------------------------------------------- ------------------ * 매개변수와 같지 않은 경우 * ------------ ------------------------------------- ------------------ * * $field의 값이 $x와 같지 않은 문서를 가져옵니다. * * @usage = $this->mongo_db-> where_between('foo', 20, 30);*/
  188. 공개 함수 where_ne($field = "", $x) {
  189. $this->where_init($field);
  190. $this->wheres[$field]['$ne'] = $x;
  191. return($this);
  192. }
  193. /*** ------------------------------------------------- ------------------ * 어디서 또는 * --------------- ------------------------------------- --------------- * * $field의 값이 하나 이상의 값에 있는 문서 가져오기 * * @usage = $this->mongo_db->where_or(' foo', array( 'foo', 'bar', 'blegh' );*/
  194. 공개 함수 where_or($field = "", $values) {
  195. $this->where_init($field);
  196. $this->wheres[$field]['$or'] = $values;
  197. return($this);
  198. }
  199. /*** ------------------------------------------------- ------------------ * 어디서 그리고 * --------------- ------------------------------------- --------------- * * 요소가 지정된 값과 일치하는 문서 가져오기 * * @usage = $this->mongo_db->where_and( array ( 'foo' => ; 1, 'b' => '일부 예' );*/
  200. 공개 함수 where_and($elements_values ​​= array()) {
  201. foreach ((array)$elements_values ​​as $element => $ val) {
  202. $this->wheres[$element] = $val;
  203. } return($this);
  204. }
  205. /*** ------------------------------------------------- ------------------ * MOD는 어디에 * --------------- ------------------------------------- --------------- * * $field % $mod = $result * * @usage = $this->mongo_db->where_mod( 'foo', 10 있는 문서 가져오기 , 1 );*/
  206. 공개 함수 where_mod($field, $num, $result) {
  207. $this->where_init($field);
  208. $this->wheres[$field]['$mod'] = array($num, $result);
  209. return($this);
  210. }
  211. /*** ------------------------------------------------- ------------------ * 사이즈는 * --------------- ------------------------------------- --------------- * * 필드 크기가 지정된 $size int인 문서 가져오기 * * @usage : $this->mongo_db->where_size(' foo', 1)->get('foobar');*/
  212. 공개 함수 where_size($field = "", $size = "") {
  213. $this->_where_init($field );
  214. $this->wheres[$field]['$size'] = $size;
  215. 반환($this);
  216. }
  217. /*** ------------------------------------------------- ------------------ * 매개변수와 유사함 * --------------- ------------------------------------- --------------- * * $field의 (문자열) 값이 값과 유사한 문서를 가져옵니다. 기본값은 * 대소문자를 구분하지 않는 검색을 허용합니다. * * @param $flags * 일반적인 정규식 플래그를 허용합니다. * i = 대소문자를 구분하지 않음 * m = 여러 줄 * x = 주석 포함 가능 * l = 로케일 * s = dotall, "." 줄 바꿈을 포함하여 모든 항목과 일치 * u = 유니코드 일치 * * @param $enable_start_wildcard * TRUE 이외의 값으로 설정되면 시작 줄 문자 "^"가 검색 값 앞에 * 추가됩니다. 이는 시작 시 값만 검색한다는 의미입니다. * 새로운 줄. * * @param $enable_end_wildcard * TRUE 이외의 값으로 설정하면 줄 끝 문자 "$"가 검색 값에 추가됩니다. 이는 줄 끝의 값만 검색한다는 것을 의미합니다. * * @usage = $this->mongo_db->like('foo', 'bar', 'im', FALSE, TRUE);*/
  218. 공개 함수 like($field = "", $value = "", $flags = "i", $enable_start_wildcard = TRUE, $enable_end_wildcard = TRUE) {
  219. $field = (문자열) Trim($field);
  220. $this->where_init($field);
  221. $value = (문자열) Trim($value);
  222. $value = quotemeta($value);
  223. if ($enable_start_wildcard !== TRUE) {
  224. $value = "^" . $값;
  225. } if ($enable_end_wildcard !== TRUE) {
  226. $value .= "$";
  227. } $regex = "/$value/$flags";
  228. $this->wheres[$field] = new MongoRegex($regex);
  229. return($this);
  230. }
  231. 공개 함수 wheres($where){
  232. $this->wheres = $where;
  233. }
  234. /*** ------------------------------------------------- ------------------ * 매개변수별 순서 * -------------- ------------------------------------- ---------------- * * 전달된 매개변수를 기준으로 문서를 정렬합니다. 값을 내림차순으로 설정하려면 * -1, FALSE, 'desc' 또는 'DESC' 값을 전달해야 합니다. 그렇지 않으면 * 1(ASC)로 설정됩니다. * * @usage = $this->mongo_db->where_between('foo', 20, 30);*/
  235. 공개 함수 order_by($fields = array()) {
  236. if (!is_array($fields) || !count($ 필드)) return ;
  237. foreach ($fields as $col => $val) {
  238. if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') {
  239. $this->sorts[$col] = -1;
  240. } else {
  241. $this->sorts[$col] = 1;
  242. }
  243. } return($this);
  244. }
  245. /*** ------------------------------------------------- ------------------ * 제한된 문서 * --------------- ------------------------------------- --------------- * * 결과 집합을 문서 수 $x로 제한 * * @usage = $this->mongo_db->limit($x);*/
  246. 공개 함수 제한($x = 99999) {
  247. if ($x !== NULL && is_numeric($x) && $ x >= 1) {
  248. $this->limit = (int) $x;
  249. } return($this);
  250. }
  251. /*** ------------------------------------------------- ------------------ * 오프셋 문서 * --------------- ------------------------------------- --------------- * * $x개의 문서를 건너뛰도록 결과 집합을 오프셋합니다. * * @usage = $this->mongo_db->offset($x);*/
  252. 공개 함수 오프셋($x = 0) {
  253. if ($x !== NULL && is_numeric($x) && $ x >= 1) {
  254. $this->offset = (int) $x;
  255. } return($this);
  256. }
  257. /*** ------------------------------------------------- ------------------ * GET_WHERE * --- ------------------------------------- -------------- * * 전달된 매개변수를 기반으로 문서 가져오기 * * @usage = $this->mongo_db->get_where('foo', array('bar' = > '뭔가'));*/
  258. 공개 함수 get_where($collection = "", $where = array(), $limit = 99999, $orderby=array()) {
  259. if (is_array($orderby) || !emptyempty($orderby)) {
  260. $order_by = $this->order_by($order_by);
  261. }
  262. return($this->where($where)->limit($limit)->get($collection));
  263. }
  264. 공개 함수 selectA($collection = "", $limit = 99999, $orderby=array()) {
  265. if(intval($limit) $limit = 999999;
  266. }
  267. $order_by = $this->order_by($orderby);
  268. $re = $this->limit($limit)->get($collection);
  269. $this->clear();
  270. return (배열)$re;
  271. }
  272. 공개 함수 listinfo($collection = "", $orderby=array(), $page=1, $pagesize=12) {
  273. $page = max(intval($page) ), 1);
  274. $offset = $pagesize * ($page - 1);
  275. $pagesizes = $offset $pagesize;
  276. $this->offset($offset);
  277. $order_by = $this->order_by($orderby);
  278. $re = $this->limit($pagesize)->get($collection);
  279. $this->limit(999999);
  280. $count = $this->count($collection);
  281. $this->pages = 페이지($count, $page, $pagesize);
  282. return (배열)$re;
  283. }
  284. /*** ------------------------------------------------- ------------------------------- * 얻다 * ---------------- ------------------------------------- -------------- * * 전달된 매개변수를 기반으로 문서 가져오기 * * @usage = $this->mongo_db->get('foo', array('bar' = > '뭔가'));*/
  285. 공개 함수 get($collection = "") {
  286. if (emptyempty($collection)) {
  287. $this- >error("MongoDB에서 문서를 검색하려면 컬렉션 이름을 전달해야 합니다.", 500);
  288. } $결과 = 배열();
  289. $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this-> ;limit)->skip((int) $this->offset)->sort($this->sorts);
  290. $returns = 배열();
  291. foreach($documents를 $doc로): $returns[] = $doc;
  292. endforeach;
  293. 반환($returns);
  294. }
  295. public function getMy($collection = "") {
  296. if (emptyempty($collection)) {
  297. $this->error("다음에서 문서를 검색하려면 MongoDB, 컬렉션 이름을 전달해야 합니다.", 500);
  298. } $결과 = 배열();
  299. $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this-> ;limit)->skip((int) $this->offset)->sort($this->sorts);
  300. $returns = 배열();
  301. foreach($documents를 $doc로): $returns[] = $doc;
  302. endforeach;
  303. $이것 -> 분명한();
  304. 반환($returns);
  305. }
  306. /*** ------------------------------------------------- ------------------------------- * 세다 * ---------------- ------------------------------------- -------------- * * 전달된 매개변수를 기반으로 문서 개수 * * @usage = $this->mongo_db->get('foo');*/
  307. 공개 함수 개수($collection = "") {
  308. if (emptyempty($collection)) {
  309. $this- >error("MongoDB에서 문서 개수를 검색하려면 컬렉션 이름을 전달해야 합니다.", 500);
  310. } $count = $this->db->{$collection}->find($this->wheres)->limit((int) $this->limit)-> Skip((int) $this->offset)->count();
  311. $this->clear();
  312. 반환($count);
  313. }
  314. /*** ------------------------------------------------- ------------------ * 삽입 * --- ------------------------------------- -------------- * * 전달된 컬렉션에 새 문서 삽입 * * @usage = $this->mongo_db->insert('foo', $data = array() );*/
  315. 공개 함수 insert($collection = "", $data = array(), $name='ID') {
  316. if (emptyempty($collection)) {
  317. $this->error("삽입할 Mongo 컬렉션을 선택하지 않았습니다.", 500);
  318. } if (count($data) == 0 || !is_array($data)) {
  319. $this->error("Mongo 컬렉션에 삽입할 항목이 없거나 삽입할 항목이 배열이 아닙니다.", 500 );
  320. } try {
  321. /**
  322. wxcity_base::load_sys_class('whtysqs','',0);
  323. $mongoseq_class = new whtysqs('creaseidsqs');
  324. $re = $mongoseq_class->query("?name=" . $collection . "&opt=put&data=1");
  325. **/
  326. $re = put_sqs('list_mongo_creaseidsqs','1');
  327. if(is_numeric($re)){
  328. $re ;
  329. $data[$name] = intval($re);
  330. }else{
  331. $data[$name] = intval(time());
  332. //die('mongosqs 오류');
  333. }
  334. $this->db->{$collection}->insert($data, array('fsync' => TRUE));
  335. $this->clear();
  336. $data[$name] 반환;
  337. } catch (MongoCursorException $e) {
  338. $this->error("MongoDB에 데이터 삽입 실패: {$e->getMessage()}", 500);
  339. }
  340. }
  341. 공개 함수 insertWithId($collection = "", $data = array()) {
  342. if (emptyempty($collection)) {
  343. $this- >error("삽입할 Mongo 컬렉션을 선택하지 않았습니다.", 500);
  344. } if (count($data) == 0 || !is_array($data)) {
  345. $this->error("Mongo 컬렉션에 삽입할 항목이 없거나 삽입할 항목이 배열이 아닙니다.", 500 );
  346. } try {
  347. $this->db->{$collection}->insert($data, array('fsync' => TRUE));
  348. $this->clear();
  349. 1을 반환합니다.
  350. } catch (MongoCursorException $e) {
  351. $this->error("MongoDB에 데이터 삽입 실패: {$e->getMessage()}", 500);
  352. }
  353. }
  354. /*** ------------------------------------------------- ------------------------------- * 업데이트 * ---------------- ------------------------------------- -------------- * * 전달된 컬렉션으로 문서 업데이트 * * @usage = $this->mongo_db->update('foo', $data = array()) ;*/
  355. 공개 함수 업데이트($collection = "", $data = array()) {
  356. if (emptyempty($collection) ) {
  357. $this->error("업데이트할 Mongo 컬렉션을 선택하지 않았습니다.", 500);
  358. } if (count($data) == 0 || !is_array($data)) {
  359. $this->error("Mongo 컬렉션에서 업데이트할 항목이 없거나 업데이트할 항목이 배열이 아닙니다.", 500 );
  360. } try {
  361. $this->db->{$collection}->update($this->wheres, array('$set' => $data), array(' fsync' => TRUE, '다중' => FALSE);
  362. $this->clear();
  363. 반환(TRUE);
  364. } catch (MongoCursorException $e) {
  365. $this->error("MongoDB로의 데이터 업데이트 실패: {$e->getMessage()}", 500);
  366. }
  367. }
  368. /*** ------------------------------------------------- ------------------ * UPDATE_ALL * --- ------------------------------------- -------------- * * 전달된 컬렉션에 새 문서 삽입 * * @usage = $this->mongo_db->update_all('foo', $data = array() );*/
  369. public function update_all($collection = "", $data = array()) {
  370. if (emptyempty( $collection)) {
  371. $this->error("업데이트할 Mongo 컬렉션을 선택하지 않았습니다.", 500);
  372. } if (count($data) == 0 || !is_array($data)) {
  373. $this->error("Mongo 컬렉션에서 업데이트할 항목이 없거나 업데이트할 항목이 배열이 아닙니다.", 500 );
  374. } try {
  375. $this->db->{$collection}->update($this->wheres, array('$set' => $data), array(' fsync' => TRUE, '다중' =>
  376. 반환(TRUE);
  377. } catch (MongoCursorException $e) {
  378. $this->error("MongoDB로의 데이터 업데이트 실패: {$e->getMessage()}", 500);
  379. }
  380. }
  381. /*** ------------------------------------------------- ------------------------------- * 삭제 * ---------------- ------------------------------------- -------------- * * 특정 기준에 따라 전달된 컬렉션에서 문서 삭제 * * @usage = $this->mongo_db->delete('foo', $data = array ());*/
  382. 공개 함수 delete($collection = "") {
  383. if (emptyempty($collection)) {
  384. $this->error("삭제할 Mongo 컬렉션을 선택하지 않았습니다.", 500);
  385. } try {
  386. $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => 진실));
  387. $this->clear();
  388. 반환(TRUE);
  389. } catch (MongoCursorException $e) {
  390. $this->error("MongoDB로의 데이터 삭제 실패: {$e->getMessage()}", 500);
  391. }
  392. }
  393. /*** ------------------------------------------------- ------------------ * DELETE_ALL * --- ------------------------------------- -------------- * * 특정 기준에 따라 전달된 컬렉션에서 모든 문서 삭제 * * @usage = $this->mongo_db->delete_all('foo', $data = 정렬());*/
  394. public function delete_all($collection = "") {
  395. if (emptyempty($collection)) {
  396. $this->error( "삭제할 Mongo 컬렉션이 선택되지 않았습니다.", 500);
  397. } try {
  398. $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => 거짓));
  399. 반환(TRUE);
  400. } catch (MongoCursorException $e) {
  401. $this->error("MongoDB로의 데이터 삭제 실패: {$e->getMessage()}", 500);
  402. }
  403. }
  404. /*** ------------------------------------------------- ------------------ * ADD_INDEX * --- ------------------------------------- -------------- * * 선택적 매개변수를 사용하여 컬렉션의 키 인덱스를 확인합니다. 값을 내림차순으로 설정하려면 * -1, FALSE, 'desc' 또는 'DESC' 값을 전달해야 합니다. 그렇지 않으면 * 1(ASC)로 설정됩니다. * * @usage = $this->mongo_db->add_index($collection, array('first_name' => 'ASC', 'last_name' => -1), array('unique' => TRUE )));*/
  405. 공개 함수 add_index($collection = "", $keys = array(), $options = array()) {
  406. if (emptyempty($collection)) {
  407. $this->error("인덱스를 추가할 Mongo 컬렉션이 지정되지 않았습니다.", 500);
  408. } if (emptyempty($keys) || !is_array($keys)) {
  409. $this->error("키가 지정되지 않았기 때문에 MongoDB 컬렉션에 인덱스를 생성할 수 없습니다.", 500);
  410. } foreach ($keys as $col => $val) {
  411. if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') {
  412. $keys[$col] = -1;
  413. } else {
  414. $keys[$col] = 1;
  415. }
  416. } if ($this->db->{$collection}->ensureIndex($keys, $options) == TRUE) {
  417. $this->clear() ;
  418. return($this);
  419. } else {
  420. $this->error("MongoDB 컬렉션에 인덱스를 추가하려고 할 때 오류가 발생했습니다.", 500);
  421. }
  422. }
  423. /*** ------------------------------------------------- ------------------ * REMOVE_INDEX * --- ------------------------------------- -------------- * * 컬렉션에 있는 키의 인덱스를 제거합니다. 값을 내림차순으로 설정하려면 * -1, FALSE, 'desc' 또는 'DESC' 값을 전달해야 합니다. 그렇지 않으면 * 1(ASC)로 설정됩니다. * * @usage = $this->mongo_db->remove_index($collection, array('first_name' => 'ASC', 'last_name' => -1));*/
  424. 공개 함수 Remove_index($collection = "", $keys = array()) {
  425. if (emptyempty( $collection)) {
  426. $this->error("인덱스를 제거할 Mongo 컬렉션이 지정되지 않았습니다.", 500);
  427. } if (emptyempty($keys) || !is_array($keys)) {
  428. $this->error("지정된 키가 없기 때문에 MongoDB 컬렉션에서 인덱스를 제거할 수 없습니다.", 500);
  429. } if ($this->db->{$collection}->deleteIndex($keys, $options) == TRUE) {
  430. $this->clear();
  431. return($this);
  432. } else {
  433. $this->error("MongoDB 컬렉션에서 인덱스를 제거하려고 할 때 오류가 발생했습니다.", 500);
  434. }
  435. }
  436. /*** ------------------------------------------------- ------------------ * REMOVE_ALL_INDEXES * --- ------------------------------------- -------------- * * 컬렉션에서 모든 인덱스를 제거합니다. * * @usage = $this->mongo_db->remove_all_index($collection);*/
  437. 공개 함수 Remove_all_indexes($collection = "") {
  438. if (emptyempty($collection)) {
  439. $this->error("모든 인덱스를 제거하기 위해 지정된 Mongo 컬렉션이 없습니다.", 500);
  440. } $this->db->{$collection}->deleteIndexes();
  441. $this->clear();
  442. return($this);
  443. }
  444. /*** ------------------------------------------------- ------------------ * LIST_INDEXES * --- ------------------------------------- -------------- * * 컬렉션의 모든 인덱스를 나열합니다. * * @usage = $this->mongo_db->list_indexes($collection);*/
  445. public function list_indexes($collection = "") {
  446. if (emptyempty($collection)) {
  447. $this->error( "모든 인덱스를 제거하도록 지정된 Mongo 컬렉션이 없습니다.", 500);
  448. } return($this->db->{$collection}->getIndexInfo());
  449. }
  450. /*** ------------------------------------------------- ------------------ * 드롭 컬렉션 * --------------- ------------------------------------- --------------- * * 데이터베이스에서 지정된 컬렉션을 제거합니다. * 제작 과정에서 매우 큰 문제가 발생할 수 있으므로 주의하세요!*/
  451. 공개 함수 drop_collection($collection = "") {
  452. if (emptyempty($collection)) {
  453. $this- >error("데이터베이스에서 삭제하도록 지정된 Mongo 컬렉션이 없습니다.", 500);
  454. } $this->db->{$collection}->drop();
  455. TRUE를 반환합니다.
  456. }
  457. /*** ------------------------------------------------- ------------------------------- * 분명한 * ---------------- ------------------------------------- -------------- * * 클래스 변수를 기본 설정으로 재설정합니다.*/
  458. 개인 함수clear() {
  459. $this->selects = array();
  460. $this->wheres = 배열();
  461. $this->limit = NULL;
  462. $this->offset = NULL;
  463. $this->sorts = 배열();
  464. }
  465. /*** ------------------------------------------------- ------------------ * 초기화 프로그램의 위치 * --------------- ------------------------------------- --------------- * * $wheres array()에 삽입할 매개변수를 준비합니다.*/
  466. 비공개 함수 where_init($param) {
  467. if (!isset($this->wheres[$param])) {
  468. $this->wheres[$param] = 배열();
  469. }
  470. }
  471. 공개 함수 오류($str, $t) {
  472. echo $str;
  473. 종료;
  474. }
  475. }
  476. ?>
复代码

使用范例
  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, 몽고디비


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在Laravel中使用Flash會話數據在Laravel中使用Flash會話數據Mar 12, 2025 pm 05:08 PM

Laravel使用其直觀的閃存方法簡化了處理臨時會話數據。這非常適合在您的應用程序中顯示簡短的消息,警報或通知。 默認情況下,數據僅針對後續請求: $請求 -

PHP記錄:PHP日誌分析的最佳實踐PHP記錄:PHP日誌分析的最佳實踐Mar 10, 2025 pm 02:32 PM

PHP日誌記錄對於監視和調試Web應用程序以及捕獲關鍵事件,錯誤和運行時行為至關重要。它為系統性能提供了寶貴的見解,有助於識別問題並支持更快的故障排除

php中的捲曲:如何在REST API中使用PHP捲曲擴展php中的捲曲:如何在REST API中使用PHP捲曲擴展Mar 14, 2025 am 11:42 AM

PHP客戶端URL(curl)擴展是開發人員的強大工具,可以與遠程服務器和REST API無縫交互。通過利用Libcurl(備受尊敬的多協議文件傳輸庫),PHP curl促進了有效的執行

簡化的HTTP響應在Laravel測試中模擬了簡化的HTTP響應在Laravel測試中模擬了Mar 12, 2025 pm 05:09 PM

Laravel 提供简洁的 HTTP 响应模拟语法,简化了 HTTP 交互测试。这种方法显著减少了代码冗余,同时使您的测试模拟更直观。 基本实现提供了多种响应类型快捷方式: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

在Codecanyon上的12個最佳PHP聊天腳本在Codecanyon上的12個最佳PHP聊天腳本Mar 13, 2025 pm 12:08 PM

您是否想為客戶最緊迫的問題提供實時的即時解決方案? 實時聊天使您可以與客戶進行實時對話,並立即解決他們的問題。它允許您為您的自定義提供更快的服務

解釋PHP中晚期靜態結合的概念。解釋PHP中晚期靜態結合的概念。Mar 21, 2025 pm 01:33 PM

文章討論了PHP 5.3中介紹的PHP中的晚期靜態結合(LSB),允許靜態方法的運行時間分辨率調用以更靈活的繼承。 LSB的實用應用和潛在的觸摸

自定義/擴展框架:如何添加自定義功能。自定義/擴展框架:如何添加自定義功能。Mar 28, 2025 pm 05:12 PM

本文討論了將自定義功能添加到框架上,專注於理解體系結構,識別擴展點以及集成和調試的最佳實踐。

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脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。