찾다
백엔드 개발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['使用者名稱']);
  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 = trim($connection_string); > /*** ------------------------------------------------- ------------------------------- * Switch_db * ---------------- -------------------------------------------------- -------------- * * 從預設資料庫切換到不同的資料庫*/
  103. public function switch_db($database = '') {
  104. if (emptyempty($database)) {
  105. $this- >error(" 切換MongoDB資料庫,必須指定新的資料庫名稱", 500) ;
  106. } $this->dbname = $database;
  107. 嘗試{
  108. $this->db = $this->connection->{$this->dbname };
  109. 回傳(真) ;
  110. } catch (Exception $e) {
  111. $this->error(" 無法切換Mongo 資料庫:{$e->getMessage()}", 500);
  112. }
  113. }
  114. /*** ------------------------------------------------- ------------------------------- * 選擇欄位* --------------- -------------------------------------------------- --------------- * * 決定在查詢過程中包含哪些欄位或排除哪些欄位。 * 目前,不能同時包含和排除,因此 * $includes 陣列將優先於 $excludes 陣列。 如果您只想選擇要排除的字段,請將 $includes 保留為空 array()。 * * @usage: $this->mongo_db->select(array('foo', 'bar'))->get('foobar');*/
  115. public function select($includes = array(), $excludes = array()) {
  116. if (! is_array($includes)) {
  117. $includes = array()
  118. }
  119. if (!is_array($excludes)) {
  120. $excludes = array()
  121. } if (!emptyempty($includes)) {
  122. foreach ($includes as $col) {
  123. $this->selects[$col] = 1;
  124. }
  125. } else {
  126. foreach ($excludes as $col) {
  127. $this->selects[$col] = 0;
  128. }
  129. } return($this);
  130. }
  131. /*** ------------------------------------------------- ------------------------------- * 參數所在* --------------- -------------------------------------------------- ---------------- * * 根據這些搜尋參數取得文件。 $wheres 數組應該是一個關聯數組,其中字段作為鍵,值作為搜尋條件。 * * @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar');*/
  132. public function where($wheres = array()) {
  133. foreach ((array)$wheres as $wh => $ val ) {
  134. $this->wheres[$wh] = $val;
  135. } return($this);
  136. }
  137. /*** ------------------------------------------------- ------------------ * WHERE_IN 매개변수 * --------------- ------------------------------------- --------------- * * $field의 값이 주어진 $in array()에 있는 문서를 가져옵니다. * * @usage = $this->mongo_db->where_in('foo', array('bar', 'zoo', 'blah'))->get('foobar');*/
  138. 공용 함수 where_in($field = "", $in = array()) {
  139. $this->where_init($field);
  140. $this->wheres[$field]['$in'] = $in;
  141. return($this);
  142. }
  143. /*** ------------------------------------------------- ------------------ * WHERE_NOT_IN 매개변수 * --------------- ------------------------------------- --------------- * * $field의 값이 주어진 $in array()에 없는 문서를 가져옵니다. * * @usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo', 'blah'))->get('foobar');*/
  144. 공개 함수 where_not_in($field = "", $in = array()) {
  145. $this->where_init($ 필드);
  146. $this->wheres[$field]['$nin'] = $in;
  147. return($this);
  148. }
  149. /*** ------------------------------------------------- ------------------ * 매개변수보다 큰 경우 * ------------- ------------------------------------- ----------------- * * $field의 값이 $x보다 큰 문서 가져오기 * * @usage = $this->mongo_db->where_gt( '푸', 20);*/
  150. 공개 함수 where_gt($field = "", $x) {
  151. $this->where_init($field);
  152. $this->wheres[$field]['$gt'] = $x;
  153. return($this);
  154. }
  155. /*** ------------------------------------------------- ------------------ * 매개변수보다 크거나 같은 경우 * ---------- ------------------------------------- ------- * * $field의 값이 $x보다 크거나 같은 문서를 가져옵니다. * * @usage = $this-> mongo_db->where_gte('foo', 20);*/
  156. 공개 함수 where_gte($field = "", $x) {
  157. $this->where_init($field);
  158. $this->wheres[$field]['$gte'] = $x;
  159. return($this);
  160. }
  161. /*** ------------------------------------------------- ------------------ * 매개변수보다 작은 경우 * ------------- ------------------------------------- ----------------- * * $field의 값이 $x보다 작은 문서 가져오기 * * @usage = $this->mongo_db->where_lt( '푸', 20);*/
  162. 공개 함수 where_lt($field = "", $x) {
  163. $this->where_init($field);
  164. $this->wheres[$field]['$lt'] = $x;
  165. return($this);
  166. }
  167. /*** ------------------------------------------------- ------------------ * 매개변수보다 작거나 같은 경우 * ---------- ------------------------------------- ------- * * $field의 값이 $x보다 작거나 같은 문서 가져오기 * * @usage = $this-> mongo_db->where_lte('foo', 20);*/
  168. 공개 함수 where_lte($field = "", $x) {
  169. $this->where_init($field);
  170. $this->wheres[$field]['$lte'] = $x;
  171. return($this);
  172. }
  173. /*** ------------------------------------------------- ------------------ * 매개변수 사이 * -------------- ------------------------------------- ---------------- * * $field의 값이 $x와 $y 사이에 있는 문서 가져오기 * * @usage = $this->mongo_db->where_between ('푸', 20, 30);*/
  174. 공개 함수 where_between($field = "", $x, $y) {
  175. $this->where_init($field );
  176. $this->wheres[$field]['$gte'] = $x;
  177. $this->wheres[$field]['$lte'] = $y;
  178. return($this);
  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 = 匹配unicode * * @param $enable_start_wildcard * 如果設定為TRUE 以外的任何內容,則在搜尋值前面新增起始行字元“^”,表示僅搜尋開頭處的值* 一新行。 * * @param $enable_end_wildcard * 如果設定為 TRUE 以外的任何值,則結束行字元「$」將附加到搜尋值,表示僅搜尋行末尾的值。 * * @usage = $this->mongo_db->like('foo', 'bar', 'im', FALSE, TRUE);*/
  218. 公用函數如($field = "", $value = "", $flags = "i", $enable_start_wildcard = TRUE, $enable_end_wildcard = TRUE) {
  219. $field = (string) 修剪($field);
  220. $this->where_init($field);
  221. $值 = (字串) 修剪($值);
  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. 返回($this);
  230. }
  231. public function wheres($where){
  232. $this->wheres = $where;
  233. }
  234. /*** ------------------------------------------------- ------------------------------- * 依參數排序 * -------------- -------------------------------------------------- ---------------- * * 根據傳遞的參數對文件進行排序。若要將值設為降序,* 您必須傳遞 -1、FALSE、'desc' 或 'DESC' 值,否則它們將被 * 設定為 1 (ASC)。 * * @usage = $this->mongo_db->where_ Between('foo', 20, 30);*/
  235. public function order_by($fields = array()) {
  236. if (!is_array($fields) || !count($ ) ) 欄位))回傳;
  237. foreach ($fields as $col => $val) {
  238. if ($val == -1 || $val === FALSE || strtolower($val) = = 'desc') {
  239. $this->sorts[$col] = -1; } else {
  240. $this->sorts[$col] = 1;
  241. }
  242. } return( $this); }
  243. /*** ------------------------------------------------- ------------------------------- * 限製檔案* --------------- -------------------------------------------------- --------------- * * 將結果集限制為$x 個文件* * @usage = $this->mongo_db->limit($x);*/
  244. 公用函數limit($x = 99999) {
  245. if ($x !== NULL && is_numeric ($x) && $ x >= 1) {
  246. $this->limit = (int) $x;
  247. } return($this); }
  248. /** * ------------------------------------------------- ------------------------------- * 抵銷文件 * --------------- -------------------------------------------------- --------------- * * 偏移結果集以跳過$x 個文件* * @usage = $this->mongo_db->offset($x);*/
  249. public function offset($x = 0) {
  250. if ($x !== NULL && is_numeric($x) && $ x >= 1) {
  251. $this-> offset = (int) $x;
  252. } return($this)
  253. }
  254. /*** ------------------------------------------------- ------------------------------------------- * 到達地點 * --- ------------- ------------------------------------- ------------- -------------- * * 根據傳入的參數取得文件* * @usage = $this->mongo_db->get_where( 'foo', array('bar' = >「某事」));*/
  255. public function get_where($collection = "", $ where = array(), $limit = 99999, $orderby=array()) {
  256. if (is_array($orderby) || !emptyempty($orderby)) {
  257. $order_by = $this->order_by ($order_by);
  258. }
  259. return($this->where($where)->limit($limit)->get($collection));
  260. }
  261. public function selectA( $collection = "", $limit = 99999, $orderby=array()) {
  262. if(intval($limit) $limit = 999999;
  263. }
  264. $order_by = $this->order_by($orderby);
  265. $re = $this->limit($limit)->get($collection);
  266. $this->clear();
  267. return (배열)$re;
  268. }
  269. 공개 함수 listinfo($collection = "", $orderby=array(), $page=1, $pagesize=12) {
  270. $page = max(intval($page) ), 1);
  271. $offset = $pagesize * ($page - 1);
  272. $pagesizes = $offset $pagesize;
  273. $this->offset($offset);
  274. $order_by = $this->order_by($orderby);
  275. $re = $this->limit($pagesize)->get($collection);
  276. $this->limit(999999);
  277. $count = $this->count($collection);
  278. $this->pages = 페이지($count, $page, $pagesize);
  279. return (배열)$re;
  280. }
  281. /*** ------------------------------------------------- ------------------------------- * 얻다 * ---------------- ------------------------------------- -------------- * * 전달된 매개변수를 기반으로 문서 가져오기 * * @usage = $this->mongo_db->get('foo', array('bar' = > '뭔가'));*/
  282. 공개 함수 get($collection = "") {
  283. if (emptyempty($collection)) {
  284. $this- >error("MongoDB에서 문서를 검색하려면 컬렉션 이름을 전달해야 합니다.", 500);
  285. } $결과 = 배열();
  286. $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this-> ;limit)->skip((int) $this->offset)->sort($this->sorts);
  287. $returns = 배열();
  288. foreach($documents를 $doc로): $returns[] = $doc;
  289. endforeach;
  290. 반환($returns);
  291. }
  292. public function getMy($collection = "") {
  293. if (emptyempty($collection)) {
  294. $this->error("다음에서 문서를 검색하려면 MongoDB, 컬렉션 이름을 전달해야 합니다.", 500);
  295. } $결과 = 배열();
  296. $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this-> ;limit)->skip((int) $this->offset)->sort($this->sorts);
  297. $returns = 배열();
  298. foreach($documents를 $doc로): $returns[] = $doc;
  299. endforeach;
  300. $이것 -> 분명한();
  301. 반환($returns);
  302. }
  303. /*** ------------------------------------------------- ------------------------------- * 세다 * ---------------- ------------------------------------- -------------- * * 전달된 매개변수를 기반으로 문서 개수 * * @usage = $this->mongo_db->get('foo');*/
  304. 공개 함수 개수($collection = "") {
  305. if (emptyempty($collection)) {
  306. $this- >error("MongoDB에서 문서 개수를 검색하려면 컬렉션 이름을 전달해야 합니다.", 500);
  307. } $count = $this->db->{$collection}->find($this->wheres)->limit((int) $this->limit)-> Skip((int) $this->offset)->count();
  308. $this->clear();
  309. 반환($count);
  310. }
  311. /*** ------------------------------------------------- ------------------ * 삽입 * --- ------------------------------------- -------------- * * 전달된 컬렉션에 새 문서 삽입 * * @usage = $this->mongo_db->insert('foo', $data = array() );*/
  312. 공개 함수 insert($collection = "", $data = array(), $name='ID') {
  313. if (emptyempty($collection)) {
  314. $this->error("삽입할 Mongo 컬렉션을 선택하지 않았습니다.", 500);
  315. } if (count($data) == 0 || !is_array($data)) {
  316. $this->error("Mongo 컬렉션에 삽입할 항목이 없거나 삽입할 항목이 배열이 아닙니다.", 500 );
  317. } try {
  318. /**
  319. wxcity_base::load_sys_class('whtysqs','',0);
  320. $mongoseq_class = new whtysqs('creaseidsqs');
  321. $re = $mongoseq_class->query("?name=" . $collection . "&opt=put&data=1");
  322. **/
  323. $re = put_sqs('list_mongo_creaseidsqs','1');
  324. if(is_numeric($re)){
  325. $re ;
  326. $data[$name] = intval($re);
  327. }else{
  328. $data[$name] = intval(time());
  329. //die('mongosqs 오류');
  330. }
  331. $this->db->{$collection}->插入($data, array('fsync' => TRUE));
  332. $this->clear();
  333. 回傳$data[$name];
  334. } catch (MongoCursorException $e) {
  335. $this->error("將資料插入MongoDB 失敗:{$e->getMessage()}", 500);
  336. }
  337. }
  338. public function insertWithId($ collection = "", $data = array()) {
  339. if (emptyempty($collection)) {
  340. $this- >error("沒有選擇要插入的Mongo 集合", 500);
  341. } if (count($data) == 0 || !is_array($data)) {
  342. $this->error("Nothing to insert into Mongo collection or insert is not an array", 500 );
  343. } try {
  344. $this->db->{$collection}->insert($data, array('fsync' => TRUE));
  345. $this->clear();
  346. 回傳1;
  347. } catch (MongoCursorException $e) {
  348. $this->error("將資料插入MongoDB 失敗:{$e->getMessage()}", 500);
  349. }
  350. }
  351. /*** ------------------------------------------------- - - - - - - - - - - - - - - - - * 更新* - - - - - - - - ----------------------- --------------------------- -------------- * * 將文件更新到傳遞的集合中* * @usage = $this->mongo_db->update('foo', $data = array()) ;*/
  352. public function update($collection = "", $data = array()) {
  353. if (emptyempty($collection) ) {
  354. $ this->error("沒有選擇要更新的Mongo 集合", 500);
  355. } if (count($data) == 0 || !is_array($data)) {
  356. $this->error ("Mongo 集合中沒有要更新的內容或更新不是陣列", 500 );
  357. } try {
  358. $this->db->{$collection}->update($this->wheres, array ('$set' => $data), array(' fsync' => TRUE,'多個' => FALSE));
  359. $this->clear();
  360. 回傳(真);
  361. } catch (MongoCursorException $e) {
  362. $this->error("將資料更新至MongoDB 失敗:{$e->getMessage()}", 500);
  363. }
  364. }
  365. /*** ------------------------------------------------- ------------------------------- * UPDATE_ALL * ---------------- -------------------------------------------------- -------------- * * 將新文件插入傳遞的集合* * @usage = $this->mongo_db->update_all('foo', $data = array() ) ;*/
  366. public function update_all($collection = "", $data = array()) {
  367. if (emptyempty( $collection)) {
  368. $ this->error("沒有選擇要更新的Mongo 集合", 500);
  369. } if (count($data) == 0 || !is_array($data)) {
  370. $this->error ("Mongo 集合中沒有要更新的內容或更新不是陣列", 500 );
  371. } try {
  372. $this->db->{$collection}->update($this->wheres, array ('$set' => $data), array(' fsync' => TRUE, '多個' => TRUE);
  373. 回傳(真);
  374. } catch (MongoCursorException $e) {
  375. $this->error("將資料更新至MongoDB 失敗:{$e->getMessage()}", 500);
  376. }
  377. }
  378. /*** ------------------------------------------------- - - - - - - - - - - - - - - - - * 刪除* - - - - - - - - ----------------------- --------------------------- -------------- * * 依特定條件從傳遞的集合中刪除文件* * @usage = $this->mongo_db->delete('foo', $data = array ());* /
  379. public function delete($collection = "") {
  380. if (emptyempty($collection)) {
  381. $this->error("沒有選擇要刪除的Mongo 集合", 500);
  382. } try {
  383. $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' =>;真的));
  384. $this->clear();
  385. 回傳(真);
  386. } catch (MongoCursorException $e) {
  387. $this->error("刪除MongoDB 資料失敗:{$e->getMessage ()}", 500);
  388. }
  389. }
  390. /*** ------------------------------------------------- ------------------ * DELETE_ALL * --- ------------------------------------- -------------- * * 특정 기준에 따라 전달된 컬렉션에서 모든 문서 삭제 * * @usage = $this->mongo_db->delete_all('foo', $data = 정렬());*/
  391. public function delete_all($collection = "") {
  392. if (emptyempty($collection)) {
  393. $this->error( "삭제할 Mongo 컬렉션이 선택되지 않았습니다.", 500);
  394. } try {
  395. $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => 거짓));
  396. 반환(TRUE);
  397. } catch (MongoCursorException $e) {
  398. $this->error("MongoDB로의 데이터 삭제 실패: {$e->getMessage()}", 500);
  399. }
  400. }
  401. /*** ------------------------------------------------- ------------------ * 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 )));*/
  402. 공개 함수 add_index($collection = "", $keys = array(), $options = array()) {
  403. if (emptyempty($collection)) {
  404. $this->error("인덱스를 추가할 Mongo 컬렉션이 지정되지 않았습니다.", 500);
  405. } if (emptyempty($keys) || !is_array($keys)) {
  406. $this->error("키가 지정되지 않았기 때문에 MongoDB 컬렉션에 인덱스를 생성할 수 없습니다.", 500);
  407. } foreach ($keys as $col => $val) {
  408. if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') {
  409. $keys[$col] = -1;
  410. } else {
  411. $keys[$col] = 1;
  412. }
  413. } if ($this->db->{$collection}->ensureIndex($keys, $options) == TRUE) {
  414. $this->clear() ;
  415. return($this);
  416. } else {
  417. $this->error("MongoDB 컬렉션에 인덱스를 추가하려고 할 때 오류가 발생했습니다.", 500);
  418. }
  419. }
  420. /*** ------------------------------------------------- ------------------ * REMOVE_INDEX * --- ------------------------------------- -------------- * * 컬렉션에 있는 키의 인덱스를 제거합니다. 값을 내림차순으로 설정하려면 * -1, FALSE, 'desc' 또는 'DESC' 값을 전달해야 합니다. 그렇지 않으면 * 1(ASC)로 설정됩니다. * * @usage = $this->mongo_db->remove_index($collection, array('first_name' => 'ASC', 'last_name' => -1));*/
  421. 공개 함수 Remove_index($collection = "", $keys = array()) {
  422. if (emptyempty( $collection)) {
  423. $this->error("인덱스를 제거할 Mongo 컬렉션이 지정되지 않았습니다.", 500);
  424. } if (emptyempty($keys) || !is_array($keys)) {
  425. $this->error("지정된 키가 없기 때문에 MongoDB 컬렉션에서 인덱스를 제거할 수 없습니다.", 500);
  426. } if ($this->db->{$collection}->deleteIndex($keys, $options) == TRUE) {
  427. $this->clear();
  428. return($this);
  429. } else {
  430. $this->error("MongoDB 컬렉션에서 인덱스를 제거하려고 할 때 오류가 발생했습니다.", 500);
  431. }
  432. }
  433. /*** ------------------------------------------------- ------------------ * REMOVE_ALL_INDEXES * --- ------------------------------------- -------------- * * 컬렉션에서 모든 인덱스를 제거합니다. * * @usage = $this->mongo_db->remove_all_index($collection);*/
  434. 공개 함수 Remove_all_indexes($collection = "") {
  435. if (emptyempty($collection)) {
  436. $this->error("모든 인덱스를 제거하기 위해 지정된 Mongo 컬렉션이 없습니다.", 500);
  437. } $this->db->{$collection}->deleteIndexes();
  438. $this->clear();
  439. return($this);
  440. }
  441. /*** ------------------------------------------------- ------------------------------- * LIST_INDEXES * ---------------- -------------------------------------------------- -------------- * * 列出集合中的所有索引。 * * @usage = $this->mongo_db->list_indexes($collection);*/
  442. public function list_indexes($collection = "") {
  443. if (emptyempty($collection)) {
  444. $this->error( “沒有指定要從中刪除所有索引的Mongo 集合」, 500);
  445. } return($this->db->{$collection}->getIndexInfo());
  446. }
  447. / *** ------------------------------------------------- ------------------------------- * 刪除收藏 * --------------- -------------------------------------------------- --------------- * * 從資料庫中刪除指定的集合。 請小心,因為這 * 在生產中可能會出現一些非常大的問題!*/
  448. public function drop_collection($collection = "") {
  449. if (emptyempty($collection)) {
  450. $this- >錯誤(「沒有指定從資料庫中刪除的Mongo 集合」, 500);
  451. } $this->db->{$collection}->drop();
  452. 回傳TRUE;
  453. }
  454. /*** ------------------------------------------------- - - - - - - - - - - - - - - - - * 清除* - - - - - - - - ----------------------- --------------------------- -------------- * * 將類別變數重設為默認設定 */
  455. private function clear() {
  456. $this->selects = array();
  457. $this->wheres = array();
  458. $this->limit = NULL;
  459. $this->offset = NULL;
  460. $this->sorts = array();
  461. }
  462. /*** ------------------------------------------------- ------------------------------- * 初始化器所在位置* ------------- -- ------------------------------------------------ -- --------------- * * 準備參數以插入$wheres array() 中。*/
  463. private function where_init($param) {
  464. if (!isset($this->wheres[$param])) {
  465. $this->wheres[$param] = array();
  466. }
  467. }
  468. 公用函數錯誤($str, $t) {
  469. echo $str;
  470. 退出;
  471. }
  472. }
  473. ? >
複製程式碼

使用範例
  1. $table_name=trim(strtolower($this->table_name));
  2. $this->mongo_db->where($where);
  3. $this->mongo_db->where($where);
  4. $order=!emptyempty($order)?array('AID'=>'DESC'):array('AID'=>'ASC');//升序降序
$infos=$ this->mongo_db ->listinfo($table_name,$order,$page,$pagesize);
複製程式碼

PHP、MongoDB


성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP의 초록 클래스 또는 인터페이스에 대한 특성과 언제 특성을 사용 하시겠습니까?PHP의 초록 클래스 또는 인터페이스에 대한 특성과 언제 특성을 사용 하시겠습니까?Apr 10, 2025 am 09:39 AM

PHP에서, 특성은 방법 재사용이 필요하지만 상속에 적합하지 않은 상황에 적합합니다. 1) 특성은 클래스에서 다중 상속의 복잡성을 피할 수 있도록 수많은 방법을 허용합니다. 2) 특성을 사용할 때는 대안과 키워드를 통해 해결할 수있는 방법 충돌에주의를 기울여야합니다. 3) 성능을 최적화하고 코드 유지 보수성을 향상시키기 위해 특성을 과도하게 사용해야하며 단일 책임을 유지해야합니다.

DIC (Dependency Injection Container) 란 무엇이며 PHP에서 사용하는 이유는 무엇입니까?DIC (Dependency Injection Container) 란 무엇이며 PHP에서 사용하는 이유는 무엇입니까?Apr 10, 2025 am 09:38 AM

의존성 주입 컨테이너 (DIC)는 PHP 프로젝트에 사용하기위한 객체 종속성을 관리하고 제공하는 도구입니다. DIC의 주요 이점에는 다음이 포함됩니다. 1. 디커플링, 구성 요소 독립적 인 코드는 유지 관리 및 테스트가 쉽습니다. 2. 유연성, 의존성을 교체 또는 수정하기 쉽습니다. 3. 테스트 가능성, 단위 테스트를 위해 모의 객체를 주입하기에 편리합니다.

SPL SplfixedArray 및 일반 PHP 어레이에 비해 성능 특성을 설명하십시오.SPL SplfixedArray 및 일반 PHP 어레이에 비해 성능 특성을 설명하십시오.Apr 10, 2025 am 09:37 AM

SplfixedArray는 PHP의 고정 크기 배열로, 고성능 및 메모리 사용이 필요한 시나리오에 적합합니다. 1) 동적 조정으로 인한 오버 헤드를 피하기 위해 생성 할 때 크기를 지정해야합니다. 2) C 언어 배열을 기반으로 메모리 및 빠른 액세스 속도를 직접 작동합니다. 3) 대규모 데이터 처리 및 메모리에 민감한 환경에 적합하지만 크기가 고정되어 있으므로주의해서 사용해야합니다.

PHP는 파일 업로드를 어떻게 단단히 처리합니까?PHP는 파일 업로드를 어떻게 단단히 처리합니까?Apr 10, 2025 am 09:37 AM

PHP는 $ \ _ 파일 변수를 통해 파일 업로드를 처리합니다. 보안을 보장하는 방법에는 다음이 포함됩니다. 1. 오류 확인 확인, 2. 파일 유형 및 크기 확인, 3 파일 덮어 쓰기 방지, 4. 파일을 영구 저장소 위치로 이동하십시오.

Null Coalescing 연산자 (??) 및 Null Coalescing 할당 연산자 (?? =)은 무엇입니까?Null Coalescing 연산자 (??) 및 Null Coalescing 할당 연산자 (?? =)은 무엇입니까?Apr 10, 2025 am 09:33 AM

JavaScript에서는 NullCoalescingOperator (??) 및 NullCoalescingAssignmentOperator (?? =)를 사용할 수 있습니다. 1. 2. ??= 변수를 오른쪽 피연산자의 값에 할당하지만 변수가 무효 또는 정의되지 않은 경우에만. 이 연산자는 코드 로직을 단순화하고 가독성과 성능을 향상시킵니다.

CSP (Content Security Policy) 헤더 란 무엇이며 왜 중요한가요?CSP (Content Security Policy) 헤더 란 무엇이며 왜 중요한가요?Apr 09, 2025 am 12:10 AM

CSP는 XSS 공격을 방지하고 리소스로드를 제한하여 웹 사이트 보안을 향상시킬 수 있기 때문에 중요합니다. 1.CSP는 HTTP 응답 헤더의 일부이며 엄격한 정책을 통해 악의적 인 행동을 제한합니다. 2. 기본 사용법은 동일한 원점에서 자원을로드 할 수있는 것입니다. 3. 고급 사용량은 특정 도메인 이름을 스크립트와 스타일로드 할 수 있도록하는 것과 같은보다 세밀한 전략을 설정할 수 있습니다. 4. Content-Security Policy 보고서 전용 헤더를 사용하여 CSP 정책을 디버그하고 최적화하십시오.

HTTP 요청 방법 (Get, Post, Put, Delete 등)이란 무엇이며 언제 각각을 사용해야합니까?HTTP 요청 방법 (Get, Post, Put, Delete 등)이란 무엇이며 언제 각각을 사용해야합니까?Apr 09, 2025 am 12:09 AM

HTTP 요청 방법에는 각각 리소스를 확보, 제출, 업데이트 및 삭제하는 데 사용되는 Get, Post, Put and Delete가 포함됩니다. 1. GET 방법은 리소스를 얻는 데 사용되며 읽기 작업에 적합합니다. 2. 게시물은 데이터를 제출하는 데 사용되며 종종 새로운 리소스를 만드는 데 사용됩니다. 3. PUT 방법은 리소스를 업데이트하는 데 사용되며 완전한 업데이트에 적합합니다. 4. 삭제 방법은 자원을 삭제하는 데 사용되며 삭제 작업에 적합합니다.

HTTPS 란 무엇이며 웹 애플리케이션에 중요한 이유는 무엇입니까?HTTPS 란 무엇이며 웹 애플리케이션에 중요한 이유는 무엇입니까?Apr 09, 2025 am 12:08 AM

HTTPS는 HTTP를 기반으로 보안 계층을 추가하는 프로토콜로, 주로 암호화 된 데이터를 통해 사용자 개인 정보 및 데이터 보안을 보호합니다. 작업 원칙에는 TLS 핸드 셰이크, 인증서 확인 및 암호화 된 커뮤니케이션이 포함됩니다. HTTP를 구현할 때는 인증서 관리, 성능 영향 및 혼합 콘텐츠 문제에주의를 기울여야합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는