찾다
백엔드 개발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으로 문의하세요.
절대 세션 타임 아웃의 차이점은 무엇입니까?절대 세션 타임 아웃의 차이점은 무엇입니까?May 03, 2025 am 12:21 AM

절대 세션 시간 초과는 세션 생성시 시작되며, 유휴 세션 시간 초과는 사용자가 작동하지 않아 시작합니다. 절대 세션 타임 아웃은 금융 응용 프로그램과 같은 세션 수명주기의 엄격한 제어가 필요한 시나리오에 적합합니다. 유휴 세션 타임 아웃은 사용자가 소셜 미디어와 같이 오랫동안 세션을 활성화하려는 응용 프로그램에 적합합니다.

세션이 서버에서 작동하지 않으면 어떤 조치를 취 하시겠습니까?세션이 서버에서 작동하지 않으면 어떤 조치를 취 하시겠습니까?May 03, 2025 am 12:19 AM

서버 세션 고장은 다음 단계를 따라 해결할 수 있습니다. 1. 서버 구성을 확인하여 세션이 올바르게 설정되었는지 확인하십시오. 2. 클라이언트 쿠키를 확인하고 브라우저가 지원하는지 확인하고 올바르게 보내십시오. 3. Redis와 같은 세션 스토리지 서비스가 정상적으로 작동하는지 확인하십시오. 4. 올바른 세션 로직을 보장하기 위해 응용 프로그램 코드를 검토하십시오. 이러한 단계를 통해 대화 문제를 효과적으로 진단하고 수리 할 수 ​​있으며 사용자 경험을 향상시킬 수 있습니다.

session_start () 함수의 중요성은 무엇입니까?session_start () 함수의 중요성은 무엇입니까?May 03, 2025 am 12:18 AM

session_start () iscrucialinphpformanagingUsersessions.1) itiniteSanewsessionifnoneexists, 2) ResumesAnxistessions, and3) setSasessionCookieForContInuityAcrosrequests, enablingplicationsirecationSerauthenticationAndpersonalizestContent.

세션 쿠키를 위해 httponly 플래그를 설정하는 것이 중요합니까?세션 쿠키를 위해 httponly 플래그를 설정하는 것이 중요합니까?May 03, 2025 am 12:10 AM

XSS 공격을 효과적으로 방지하고 사용자 세션 정보를 보호 할 수 있기 때문에 httponly 플래그를 설정하는 것은 세션 쿠키에 중요합니다. 구체적으로, 1) httponly 플래그는 JavaScript가 쿠키에 액세스하는 것을 방지합니다. 2) PHP 및 Flask에서 SetCookies 및 Make_response를 통해 깃발을 설정할 수 있습니다. 3) 모든 공격으로부터 방지 할 수는 없지만 전체 보안 정책의 일부가되어야합니다.

웹 개발에서 PHP 세션은 어떤 문제를 해결합니까?웹 개발에서 PHP 세션은 어떤 문제를 해결합니까?May 03, 2025 am 12:02 AM

phpssessionssolvetheproblemofmainingstateacrossmultiplehtttprequestsbystoringdataontheserversociatingititwithauniquessessionid.1) theStoredAserver-side, 일반적으로, 일반적으로 and insessionsecietoretoretrievedata.2) sessionsenhances

PHP 세션에 어떤 데이터를 저장할 수 있습니까?PHP 세션에 어떤 데이터를 저장할 수 있습니까?May 02, 2025 am 12:17 AM

phpsessionscanstorestrings, 숫자, 배열 및 객체 1.Strings : TextDatalikeUsernames.2.numbers : integorfloatsforcounters.3.arrays : listslikeshoppingcarts.4.objects : complexStructuresThatareserialized.

PHP 세션을 어떻게 시작합니까?PHP 세션을 어떻게 시작합니까?May 02, 2025 am 12:16 AM

tostartAphPessession, us

세션 재생이란 무엇이며 보안을 어떻게 개선합니까?세션 재생이란 무엇이며 보안을 어떻게 개선합니까?May 02, 2025 am 12:15 AM

세션 재생은 세션 고정 공격의 경우 사용자가 민감한 작업을 수행 할 때 새 세션 ID를 생성하고 이전 ID를 무효화하는 것을 말합니다. 구현 단계에는 다음이 포함됩니다. 1. 민감한 작업 감지, 2. 새 세션 ID 생성, 3. 오래된 세션 ID 파괴, 4. 사용자 측 세션 정보 업데이트.

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 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.