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

php封裝的mongodb操作類

Jul 25, 2016 am 08:43 AM

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

使用范例
  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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

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

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1665
14
CakePHP 教程
1424
52
Laravel 教程
1322
25
PHP教程
1270
29
C# 教程
1249
24
說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? 說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? Apr 17, 2025 am 12:06 AM

在PHP中,應使用password_hash和password_verify函數實現安全的密碼哈希處理,不應使用MD5或SHA1。1)password_hash生成包含鹽值的哈希,增強安全性。 2)password_verify驗證密碼,通過比較哈希值確保安全。 3)MD5和SHA1易受攻擊且缺乏鹽值,不適合現代密碼安全。

PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP的持久相關性:它還活著嗎? PHP的持久相關性:它還活著嗎? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

PHP和Python:代碼示例和比較 PHP和Python:代碼示例和比較 Apr 15, 2025 am 12:07 AM

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP與其他語言:比較 PHP與其他語言:比較 Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

See all articles