Maison développement back-end tutoriel php Comment encapsuler la base de données MongoDB en php

Comment encapsuler la base de données MongoDB en php

May 18, 2018 pm 03:56 PM
mongodb php 数据库

Cet article partage principalement une classe d'opération mongodb encapsulée en php. Les amis dans le besoin peuvent se référer au

code principal

<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


class mongo_db {

  private $config;
  private $connection;
  private $db;
  private $connection_string;
  private $host;
  private $port;
  private $user;
  private $pass;
  private $dbname;
  private $persist;
  private $persist_key;
  private $selects = array();
  private $wheres = array();
  private $sorts = array();
  private $limit = 999999;
  private $offset = 0;
  private $timeout = 200;
  private $key = 0;
  /**   *  --------------------------------------------------------------------------------   * CONSTRUCTOR * --------------------------------------------------------------------------------   *  * Automatically check if the Mongo PECL extension has been installed/enabled. * Generate the connection string and establish a connection to the MongoDB.  */

  public function __construct() {
    if((IS_NOSQL != 1)){
      return;
    }
    if (!class_exists(&#39;Mongo&#39;)) {
      //$this->error("The MongoDB PECL extension has not been installed or enabled", 500);
    }
    $configs =wxcity_base::load_config("cache","mongo_db");
    $num = count($configs[&#39;connect&#39;]);
    $this->timeout = trim($configs[&#39;timeout&#39;]);
    $keys = wxcity_base::load_config(&#39;double&#39;);
    $this->key = $keys[&#39;mongo_db&#39;];
    $this->config = $configs[&#39;connect&#39;][$this->key];
    $status = $this->connect();
    if($status == false)
    {
      for($i = 1; $i < $num; $i++)
      {
        $n = $this->key + $i;
        $key = $n >= $num ? $n - $num : $n;
        $this->config = $configs[&#39;connect&#39;][$key];
        $status = $this->connect();
        if($status!=false)
        {
          $keys[&#39;mongo_db&#39;] = $key ;
          $this->key = $key;
          $data = "<?php\nreturn ".var_export($keys, true).";\n?>";
          file_put_contents(WHTY_PATH.&#39;configs/double.php&#39;, $data, LOCK_EX);
          break;
        }
      }
    }
    if($status==false)
    {
      die(&#39;mongoDB not connect&#39;);
    }
  }

  function __destruct() {
    if((IS_NOSQL != 1)){
      return;
    }
    if($this->connection)
    {
      $this->connection->close();
    }
  }

  /**   *  --------------------------------------------------------------------------------   * CONNECT TO MONGODB  * --------------------------------------------------------------------------------   *  * Establish a connection to MongoDB using the connection string generated in  * the connection_string() method. If &#39;mongo_persist_key&#39; was set to true in the  * config file, establish a persistent connection. We allow for only the &#39;persist&#39;   * option to be set because we want to establish a connection immediately. */
  private function connect() {
    $this->connection_string();
    $options = array(&#39;connect&#39;=>true,&#39;timeout&#39;=>$this->timeout);
    try {
      $this->connection = new Mongo($this->connection_string, $options);
      $this->db = $this->connection->{$this->dbname};
      return($this);
    } catch (MongoConnectionException $e) {
      return false;
    }

  }
  /**   *  --------------------------------------------------------------------------------   * BUILD CONNECTION STRING * --------------------------------------------------------------------------------   *  * Build the connection string from the config file.  */
  private function connection_string() {
    $this->host = trim($this->config[&#39;hostname&#39;]);
    $this->port = trim($this->config[&#39;port&#39;]);
    $this->user = trim($this->config[&#39;username&#39;]);
    $this->pass = trim($this->config[&#39;password&#39;]);
    $this->dbname = trim($this->config[&#39;database&#39;]);
    $this->persist = trim($this->config[&#39;autoconnect&#39;]);
    $this->persist_key = trim($this->config[&#39;mongo_persist_key&#39;]);

    $connection_string = "mongodb://";
    if (emptyempty($this->host)) {
      $this->error("The Host must be set to connect to MongoDB", 500);
    } if (emptyempty($this->dbname)) {
      $this->error("The Database must be set to connect to MongoDB", 500);
    } if (!emptyempty($this->user) && !emptyempty($this->pass)) {
      $connection_string .= "{$this->user}:{$this->pass}@";
    } if (isset($this->port) && !emptyempty($this->port)) {
      $connection_string .= "{$this->host}:{$this->port}";
    } else {
      $connection_string .= "{$this->host}";
    } $this->connection_string = trim($connection_string);
  }

  /**   *  --------------------------------------------------------------------------------   * Switch_db  * --------------------------------------------------------------------------------   *  * Switch from default database to a different db  */
  public function switch_db($database = &#39;&#39;) {
    if (emptyempty($database)) {
      $this->error("To switch MongoDB databases, a new database name must be specified", 500);
    } $this->dbname = $database;
    try {
      $this->db = $this->connection->{$this->dbname};
      return(TRUE);
    } catch (Exception $e) {
      $this->error("Unable to switch Mongo Databases: {$e->getMessage()}", 500);
    }
  }

  /**   *  --------------------------------------------------------------------------------   * SELECT FIELDS  * --------------------------------------------------------------------------------   *  * Determine which fields to include OR which to exclude during the query process. * Currently, including and excluding at the same time is not available, so the   * $includes array will take precedence over the $excludes array. If you want to  * only choose fields to exclude, leave $includes an empty array().   *  * @usage: $this->mongo_db->select(array(&#39;foo&#39;, &#39;bar&#39;))->get(&#39;foobar&#39;);  */
  public function select($includes = array(), $excludes = array()) {
    if (!is_array($includes)) {
      $includes = array();
    }
    if (!is_array($excludes)) {
      $excludes = array();
    }
    if (!emptyempty($includes)) {
      foreach ($includes as $col) {
        $this->selects[$col] = 1;
      }
    } else {
      foreach ($excludes as $col) {
        $this->selects[$col] = 0;
      }
    } return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE PARAMETERS   * --------------------------------------------------------------------------------   *  * Get the documents based on these search parameters. The $wheres array should  * be an associative array with the field as the key and the value as the search  * criteria.  *  * @usage = $this->mongo_db->where(array(&#39;foo&#39; => &#39;bar&#39;))->get(&#39;foobar&#39;);  */
  public function where($wheres = array()) {
    foreach ((array)$wheres as $wh => $val) {
      $this->wheres[$wh] = $val;
    } return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE_IN PARAMETERS * --------------------------------------------------------------------------------   *  * Get the documents where the value of a $field is in a given $in array().   *  * @usage = $this->mongo_db->where_in(&#39;foo&#39;, array(&#39;bar&#39;, &#39;zoo&#39;, &#39;blah&#39;))->get(&#39;foobar&#39;); */
  public function where_in($field = "", $in = array()) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$in&#39;] = $in;
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE_NOT_IN PARAMETERS * --------------------------------------------------------------------------------   *  * Get the documents where the value of a $field is not in a given $in array().   *  * @usage = $this->mongo_db->where_not_in(&#39;foo&#39;, array(&#39;bar&#39;, &#39;zoo&#39;, &#39;blah&#39;))->get(&#39;foobar&#39;); */
  public function where_not_in($field = "", $in = array()) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$nin&#39;] = $in;
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE GREATER THAN PARAMETERS  * --------------------------------------------------------------------------------   *  * Get the documents where the value of a $field is greater than $x   *  * @usage = $this->mongo_db->where_gt(&#39;foo&#39;, 20);   */
  public function where_gt($field = "", $x) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$gt&#39;] = $x;
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE GREATER THAN OR EQUAL TO PARAMETERS  * --------------------------------------------------------------------------------   *  * Get the documents where the value of a $field is greater than or equal to $x   *  * @usage = $this->mongo_db->where_gte(&#39;foo&#39;, 20);  */
  public function where_gte($field = "", $x) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$gte&#39;] = $x;
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE LESS THAN PARAMETERS  * --------------------------------------------------------------------------------   *  * Get the documents where the value of a $field is less than $x  *  * @usage = $this->mongo_db->where_lt(&#39;foo&#39;, 20);   */
  public function where_lt($field = "", $x) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$lt&#39;] = $x;
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE LESS THAN OR EQUAL TO PARAMETERS  * --------------------------------------------------------------------------------   *  * Get the documents where the value of a $field is less than or equal to $x  *  * @usage = $this->mongo_db->where_lte(&#39;foo&#39;, 20);  */
  public function where_lte($field = "", $x) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$lte&#39;] = $x;
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE BETWEEN PARAMETERS   * --------------------------------------------------------------------------------   *  * Get the documents where the value of a $field is between $x and $y  *  * @usage = $this->mongo_db->where_between(&#39;foo&#39;, 20, 30);  */
  public function where_between($field = "", $x, $y) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$gte&#39;] = $x;
    $this->wheres[$field][&#39;$lte&#39;] = $y;
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE BETWEEN AND NOT EQUAL TO PARAMETERS  * --------------------------------------------------------------------------------   *  * Get the documents where the value of a $field is between but not equal to $x and $y *  * @usage = $this->mongo_db->where_between_ne(&#39;foo&#39;, 20, 30);   */
  public function where_between_ne($field = "", $x, $y) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$gt&#39;] = $x;
    $this->wheres[$field][&#39;$lt&#39;] = $y;
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE NOT EQUAL TO PARAMETERS  * --------------------------------------------------------------------------------   *  * Get the documents where the value of a $field is not equal to $x   *  * @usage = $this->mongo_db->where_between(&#39;foo&#39;, 20, 30);  */
  public function where_ne($field = "", $x) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$ne&#39;] = $x;
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE OR   * --------------------------------------------------------------------------------   *  * Get the documents where the value of a $field is in one or more values  *  * @usage = $this->mongo_db->where_or(&#39;foo&#39;, array( &#39;foo&#39;, &#39;bar&#39;, &#39;blegh&#39; ); */
  public function where_or($field = "", $values) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$or&#39;] = $values;
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE AND  * --------------------------------------------------------------------------------   *  * Get the documents where the elements match the specified values *  * @usage = $this->mongo_db->where_and( array ( &#39;foo&#39; => 1, &#39;b&#39; => &#39;someexample&#39; );   */
  public function where_and($elements_values = array()) {
    foreach ((array)$elements_values as $element => $val) {
      $this->wheres[$element] = $val;
    } return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE MOD  * --------------------------------------------------------------------------------   *  * Get the documents where $field % $mod = $result *  * @usage = $this->mongo_db->where_mod( &#39;foo&#39;, 10, 1 );  */
  public function where_mod($field, $num, $result) {
    $this->where_init($field);
    $this->wheres[$field][&#39;$mod&#39;] = array($num, $result);
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------  *  Where size *  --------------------------------------------------------------------------------  *  *  Get the documents where the size of a field is in a given $size int *  *  @usage : $this->mongo_db->where_size(&#39;foo&#39;, 1)->get(&#39;foobar&#39;); */
  public function where_size($field = "", $size = "") {
    $this->_where_init($field);
    $this->wheres[$field][&#39;$size&#39;] = $size;
    return ($this);
  }

  /**   *  --------------------------------------------------------------------------------   * LIKE PARAMETERS * --------------------------------------------------------------------------------   *    * Get the documents where the (string) value of a $field is like a value. The defaults   * allow for a case-insensitive search.   *  * @param $flags  * Allows for the typical regular expression flags:   *   i = case insensitive   *   m = multiline  *   x = can contain comments   *   l = locale  *   s = dotall, "." matches everything, including newlines  *   u = match unicode  *  * @param $enable_start_wildcard  * If set to anything other than TRUE, a starting line character "^" will be prepended * to the search value, representing only searching for a value at the start of   * a new line. *  * @param $enable_end_wildcard * If set to anything other than TRUE, an ending line character "$" will be appended  * to the search value, representing only searching for a value at the end of  * a line. *  * @usage = $this->mongo_db->like(&#39;foo&#39;, &#39;bar&#39;, &#39;im&#39;, FALSE, TRUE);  */
  public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = TRUE, $enable_end_wildcard = TRUE) {
    $field = (string) trim($field);
    $this->where_init($field);
    $value = (string) trim($value);
    $value = quotemeta($value);
    if ($enable_start_wildcard !== TRUE) {
      $value = "^" . $value;
    } if ($enable_end_wildcard !== TRUE) {
      $value .= "$";
    } $regex = "/$value/$flags";
    $this->wheres[$field] = new MongoRegex($regex);
    return($this);
  }

  public function wheres($where){
    $this->wheres = $where;
  }

  /**   *  --------------------------------------------------------------------------------   * ORDER BY PARAMETERS * --------------------------------------------------------------------------------   *  * Sort the documents based on the parameters passed. To set values to descending order,  * you must pass values of either -1, FALSE, &#39;desc&#39;, or &#39;DESC&#39;, else they will be  * set to 1 (ASC). *  * @usage = $this->mongo_db->where_between(&#39;foo&#39;, 20, 30);  */
  public function order_by($fields = array()) {
    if (!is_array($fields) || !count($fields)) return ;
    foreach ($fields as $col => $val) {
      if ($val == -1 || $val === FALSE || strtolower($val) == &#39;desc&#39;) {
        $this->sorts[$col] = -1;
      } else {
        $this->sorts[$col] = 1;
      }
    } return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * LIMIT DOCUMENTS * --------------------------------------------------------------------------------   *  * Limit the result set to $x number of documents  *  * @usage = $this->mongo_db->limit($x);  */
  public function limit($x = 99999) {
    if ($x !== NULL && is_numeric($x) && $x >= 1) {
      $this->limit = (int) $x;
    } return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * OFFSET DOCUMENTS   * --------------------------------------------------------------------------------   *  * Offset the result set to skip $x number of documents   *  * @usage = $this->mongo_db->offset($x); */
  public function offset($x = 0) {
    if ($x !== NULL && is_numeric($x) && $x >= 1) {
      $this->offset = (int) $x;
    } return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * GET_WHERE  * --------------------------------------------------------------------------------   *  * Get the documents based upon the passed parameters  *  * @usage = $this->mongo_db->get_where(&#39;foo&#39;, array(&#39;bar&#39; => &#39;something&#39;));  */
  public function get_where($collection = "", $where = array(), $limit = 99999, $orderby=array()) {
    if (is_array($orderby) || !emptyempty($orderby)) {
      $order_by = $this->order_by($order_by);
    }
    return($this->where($where)->limit($limit)->get($collection));
  }
  public function selectA($collection = "", $limit = 99999, $orderby=array()) {
    if(intval($limit)<1){
      $limit = 999999;
    }
    $order_by = $this->order_by($orderby);
    $re = $this->limit($limit)->get($collection);
    $this->clear();
    return (array)$re;
  }

  public function listinfo($collection = "", $orderby=array(), $page=1, $pagesize=12) {
    $page = max(intval($page), 1);
    $offset = $pagesize * ($page - 1);
    $pagesizes = $offset + $pagesize;
    $this->offset($offset);
    $order_by = $this->order_by($orderby);
    $re = $this->limit($pagesize)->get($collection);
    $this->limit(999999);
    $count = $this->count($collection);
    $this->pages = pages($count, $page, $pagesize);
    return (array)$re;
  }

  /**   *  --------------------------------------------------------------------------------   * GET * --------------------------------------------------------------------------------   *  * Get the documents based upon the passed parameters  *  * @usage = $this->mongo_db->get(&#39;foo&#39;, array(&#39;bar&#39; => &#39;something&#39;)); */
  public function get($collection = "") {
    if (emptyempty($collection)) {
      $this->error("In order to retreive documents from MongoDB, a collection name must be passed", 500);
    } $results = array();
    $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this->limit)->skip((int) $this->offset)->sort($this->sorts);
    $returns = array();
    foreach ($documents as $doc): $returns[] = $doc;
    endforeach;
    return($returns);
  }

  public function getMy($collection = "") {
    if (emptyempty($collection)) {
      $this->error("In order to retreive documents from MongoDB, a collection name must be passed", 500);
    } $results = array();
    $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this->limit)->skip((int) $this->offset)->sort($this->sorts);
    $returns = array();
    foreach ($documents as $doc): $returns[] = $doc;
    endforeach;
    $this -> clear();
    return($returns);
  }

  /**   *  --------------------------------------------------------------------------------   * COUNT  * --------------------------------------------------------------------------------   *  * Count the documents based upon the passed parameters   *  * @usage = $this->mongo_db->get(&#39;foo&#39;); */
  public function count($collection = "") {
    if (emptyempty($collection)) {
      $this->error("In order to retreive a count of documents from MongoDB, a collection name must be passed", 500);
    } $count = $this->db->{$collection}->find($this->wheres)->limit((int) $this->limit)->skip((int) $this->offset)->count();
    $this->clear();
    return($count);
  }

  /**   *  --------------------------------------------------------------------------------   * INSERT  * --------------------------------------------------------------------------------   *  * Insert a new document into the passed collection   *  * @usage = $this->mongo_db->insert(&#39;foo&#39;, $data = array()); */
  public function insert($collection = "", $data = array(), $name=&#39;ID&#39;) {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection selected to insert into", 500);
    } if (count($data) == 0 || !is_array($data)) {
      $this->error("Nothing to insert into Mongo collection or insert is not an array", 500);
    } try {
      /**
      wxcity_base::load_sys_class(&#39;whtysqs&#39;,&#39;&#39;,0);
      $mongoseq_class = new whtysqs(&#39;creaseidsqs&#39;);
      $re = $mongoseq_class->query("?name=" . $collection . "&opt=put&data=1");
       **/
      $re = put_sqs(&#39;list_mongo_creaseidsqs&#39;,&#39;1&#39;);
      if(is_numeric($re)){
        $re++;
        $data[$name] = intval($re);
      }else{
        $data[$name] = intval(time());
        //die(&#39;mongosqs error&#39;);
      }
      $this->db->{$collection}->insert($data, array(&#39;fsync&#39; => TRUE));
      $this->clear();
      return $data[$name];
    } catch (MongoCursorException $e) {
      $this->error("Insert of data into MongoDB failed: {$e->getMessage()}", 500);
    }
  }

  public function insertWithId($collection = "", $data = array()) {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection selected to insert into", 500);
    } if (count($data) == 0 || !is_array($data)) {
      $this->error("Nothing to insert into Mongo collection or insert is not an array", 500);
    } try {
      $this->db->{$collection}->insert($data, array(&#39;fsync&#39; => TRUE));
      $this->clear();
      return 1;
    } catch (MongoCursorException $e) {
      $this->error("Insert of data into MongoDB failed: {$e->getMessage()}", 500);
    }
  }
  /**   *  --------------------------------------------------------------------------------   * UPDATE  * --------------------------------------------------------------------------------   *  * Update a document into the passed collection   *  * @usage = $this->mongo_db->update(&#39;foo&#39;, $data = array()); */
  public function update($collection = "", $data = array()) {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection selected to update", 500);
    } if (count($data) == 0 || !is_array($data)) {
      $this->error("Nothing to update in Mongo collection or update is not an array", 500);
    } try {
      $this->db->{$collection}->update($this->wheres, array(&#39;$set&#39; => $data), array(&#39;fsync&#39; => TRUE, &#39;multiple&#39; => FALSE));
      $this->clear();
      return(TRUE);
    } catch (MongoCursorException $e) {
      $this->error("Update of data into MongoDB failed: {$e->getMessage()}", 500);
    }
  }

  /**   *  --------------------------------------------------------------------------------   * UPDATE_ALL  * --------------------------------------------------------------------------------   *  * Insert a new document into the passed collection   *  * @usage = $this->mongo_db->update_all(&#39;foo&#39;, $data = array()); */
  public function update_all($collection = "", $data = array()) {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection selected to update", 500);
    } if (count($data) == 0 || !is_array($data)) {
      $this->error("Nothing to update in Mongo collection or update is not an array", 500);
    } try {
      $this->db->{$collection}->update($this->wheres, array(&#39;$set&#39; => $data), array(&#39;fsync&#39; => TRUE, &#39;multiple&#39; => TRUE));
      return(TRUE);
    } catch (MongoCursorException $e) {
      $this->error("Update of data into MongoDB failed: {$e->getMessage()}", 500);
    }
  }

  /**   *  --------------------------------------------------------------------------------   * DELETE  * --------------------------------------------------------------------------------   *  * delete document from the passed collection based upon certain criteria  *  * @usage = $this->mongo_db->delete(&#39;foo&#39;, $data = array()); */
  public function delete($collection = "") {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection selected to delete from", 500);
    } try {
      $this->db->{$collection}->remove($this->wheres, array(&#39;fsync&#39; => TRUE, &#39;justOne&#39; => TRUE));
      $this->clear();
      return(TRUE);
    } catch (MongoCursorException $e) {
      $this->error("Delete of data into MongoDB failed: {$e->getMessage()}", 500);
    }
  }

  /**   *  --------------------------------------------------------------------------------   * DELETE_ALL  * --------------------------------------------------------------------------------   *  * Delete all documents from the passed collection based upon certain criteria *  * @usage = $this->mongo_db->delete_all(&#39;foo&#39;, $data = array()); */
  public function delete_all($collection = "") {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection selected to delete from", 500);
    } try {
      $this->db->{$collection}->remove($this->wheres, array(&#39;fsync&#39; => TRUE, &#39;justOne&#39; => FALSE));
      return(TRUE);
    } catch (MongoCursorException $e) {
      $this->error("Delete of data into MongoDB failed: {$e->getMessage()}", 500);
    }
  }

  /**   *  --------------------------------------------------------------------------------   * ADD_INDEX  * --------------------------------------------------------------------------------   *  * Ensure an index of the keys in a collection with optional parameters. To set values to descending order,   * you must pass values of either -1, FALSE, &#39;desc&#39;, or &#39;DESC&#39;, else they will be  * set to 1 (ASC). *  * @usage = $this->mongo_db->add_index($collection, array(&#39;first_name&#39; => &#39;ASC&#39;, &#39;last_name&#39; => -1), array(&#39;unique&#39; => TRUE));  */
  public function add_index($collection = "", $keys = array(), $options = array()) {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection specified to add index to", 500);
    } if (emptyempty($keys) || !is_array($keys)) {
      $this->error("Index could not be created to MongoDB Collection because no keys were specified", 500);
    } foreach ($keys as $col => $val) {
      if ($val == -1 || $val === FALSE || strtolower($val) == &#39;desc&#39;) {
        $keys[$col] = -1;
      } else {
        $keys[$col] = 1;
      }
    } if ($this->db->{$collection}->ensureIndex($keys, $options) == TRUE) {
      $this->clear();
      return($this);
    } else {
      $this->error("An error occured when trying to add an index to MongoDB Collection", 500);
    }
  }

  /**   *  --------------------------------------------------------------------------------   * REMOVE_INDEX   * --------------------------------------------------------------------------------   *  * Remove an index of the keys in a collection. To set values to descending order, * you must pass values of either -1, FALSE, &#39;desc&#39;, or &#39;DESC&#39;, else they will be  * set to 1 (ASC). *  * @usage = $this->mongo_db->remove_index($collection, array(&#39;first_name&#39; => &#39;ASC&#39;, &#39;last_name&#39; => -1));  */
  public function remove_index($collection = "", $keys = array()) {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection specified to remove index from", 500);
    } if (emptyempty($keys) || !is_array($keys)) {
      $this->error("Index could not be removed from MongoDB Collection because no keys were specified", 500);
    } if ($this->db->{$collection}->deleteIndex($keys, $options) == TRUE) {
      $this->clear();
      return($this);
    } else {
      $this->error("An error occured when trying to remove an index from MongoDB Collection", 500);
    }
  }

  /**   *  --------------------------------------------------------------------------------   * REMOVE_ALL_INDEXES  * --------------------------------------------------------------------------------   *  * Remove all indexes from a collection.  *  * @usage = $this->mongo_db->remove_all_index($collection);  */
  public function remove_all_indexes($collection = "") {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection specified to remove all indexes from", 500);
    } $this->db->{$collection}->deleteIndexes();
    $this->clear();
    return($this);
  }

  /**   *  --------------------------------------------------------------------------------   * LIST_INDEXES   * --------------------------------------------------------------------------------   *  * Lists all indexes in a collection.  *  * @usage = $this->mongo_db->list_indexes($collection);  */
  public function list_indexes($collection = "") {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection specified to remove all indexes from", 500);
    } return($this->db->{$collection}->getIndexInfo());
  }

  /**   *  --------------------------------------------------------------------------------   * DROP COLLECTION * --------------------------------------------------------------------------------   *  * Removes the specified collection from the database. Be careful because this   * can have some very large issues in production!  */
  public function drop_collection($collection = "") {
    if (emptyempty($collection)) {
      $this->error("No Mongo collection specified to drop from database", 500);
    } $this->db->{$collection}->drop();
    return TRUE;
  }

  /**   *  --------------------------------------------------------------------------------   * CLEAR  * --------------------------------------------------------------------------------   *  * Resets the class variables to default settings  */
  private function clear() {
    $this->selects = array();
    $this->wheres = array();
    $this->limit = NULL;
    $this->offset = NULL;
    $this->sorts = array();
  }

  /**   *  --------------------------------------------------------------------------------   * WHERE INITIALIZER  * --------------------------------------------------------------------------------   *  * Prepares parameters for insertion in $wheres array().  */
  private function where_init($param) {
    if (!isset($this->wheres[$param])) {
      $this->wheres[$param] = array();
    }
  }

  public function error($str, $t) {
    echo $str;
    exit;
  }

}

?>
Copier après la connexion

Exemples d'utilisation :

$table_name=trim(strtolower($this->table_name));
$this->mongo_db->where($where);
$order=!emptyempty($order)?array(&#39;AID&#39;=>&#39;DESC&#39;):array(&#39;AID&#39;=>&#39;ASC&#39;);//升序降序
$infos=$this->mongo_db->listinfo($table_name,$order,$page,$pagesize);
Copier après la connexion


Recommandations associées :

Détail explication des étapes de fonctionnement de la base de données PHP+mongoDB

Comment opérer dans Node.jsbase de données mongodb

Comment Node.js exploite la base de données MongoDB

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Comment déverrouiller tout dans Myrise
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Qu'est-ce que la contrefaçon de demande inter-sites (CSRF) et comment implémentez-vous la protection CSRF dans PHP? Qu'est-ce que la contrefaçon de demande inter-sites (CSRF) et comment implémentez-vous la protection CSRF dans PHP? Apr 07, 2025 am 12:02 AM

En PHP, vous pouvez prévenir efficacement les attaques du CSRF en utilisant des jetons imprévisibles. Les méthodes spécifiques comprennent: 1. Générer et intégrer les jetons CSRF dans la forme; 2. Vérifiez la validité du jeton lors du traitement de la demande.

Comment pouvez-vous empêcher une classe d'être prolongée ou une méthode d'être remplacée en PHP? (mot-clé final) Comment pouvez-vous empêcher une classe d'être prolongée ou une méthode d'être remplacée en PHP? (mot-clé final) Apr 08, 2025 am 12:03 AM

Dans PHP, le mot-clé final est utilisé pour empêcher les classes d'être héritées et les méthodes écrasées. 1) Lors du marquage de la classe comme final, la classe ne peut pas être héritée. 2) Lors du marquage de la méthode comme final, la méthode ne peut pas être réécrite par la sous-classe. L'utilisation de mots clés finaux garantit la stabilité et la sécurité de votre code.

Décrivez l'objectif et l'utilisation de l'opérateur ... (SPLAT) dans les arguments de fonction PHP et le déballage du tableau. Décrivez l'objectif et l'utilisation de l'opérateur ... (SPLAT) dans les arguments de fonction PHP et le déballage du tableau. Apr 06, 2025 am 12:07 AM

L'opérateur ... (SPLAT) dans PHP est utilisé pour déballer les paramètres et les tableaux de fonction, améliorant la simplicité et l'efficacité du code. 1) Démontage du paramètre de fonction: passez l'élément de tableau en tant que paramètre à la fonction. 2) Démontage du tableau: déballer un tableau dans un autre tableau ou en tant que paramètre de fonction.

Expliquez des types stricts (Declare (strict_types = 1);) en php. Expliquez des types stricts (Declare (strict_types = 1);) en php. Apr 07, 2025 am 12:05 AM

Les types stricts en PHP sont activés en ajoutant Declare (strict_types = 1); en haut du fichier. 1) Il force la vérification du type des paramètres de fonction et des valeurs de retour pour éviter la conversion de type implicite. 2) L'utilisation de types stricts peut améliorer la fiabilité et la prévisibilité du code, réduire les bogues et améliorer la maintenabilité et la lisibilité.

MySQL: Concepts simples pour l'apprentissage facile MySQL: Concepts simples pour l'apprentissage facile Apr 10, 2025 am 09:29 AM

MySQL est un système de gestion de base de données relationnel open source. 1) Créez une base de données et des tables: utilisez les commandes CreateDatabase et CreateTable. 2) Opérations de base: insérer, mettre à jour, supprimer et sélectionner. 3) Opérations avancées: jointure, sous-requête et traitement des transactions. 4) Compétences de débogage: vérifiez la syntaxe, le type de données et les autorisations. 5) Suggestions d'optimisation: utilisez des index, évitez de sélectionner * et utilisez les transactions.

L'avenir de PHP: adaptations et innovations L'avenir de PHP: adaptations et innovations Apr 11, 2025 am 12:01 AM

L'avenir de PHP sera réalisé en s'adaptant aux nouvelles tendances technologiques et en introduisant des fonctionnalités innovantes: 1) s'adapter aux architectures de cloud computing, de conteneurisation et de microservice, en prenant en charge Docker et Kubernetes; 2) introduire des compilateurs JIT et des types d'énumération pour améliorer l'efficacité des performances et du traitement des données; 3) Optimiser en continu les performances et promouvoir les meilleures pratiques.

PHP vs Python: comprendre les différences PHP vs Python: comprendre les différences Apr 11, 2025 am 12:15 AM

PHP et Python ont chacun leurs propres avantages, et le choix doit être basé sur les exigences du projet. 1.Php convient au développement Web, avec une syntaxe simple et une efficacité d'exécution élevée. 2. Python convient à la science des données et à l'apprentissage automatique, avec une syntaxe concise et des bibliothèques riches.

Méthode de Navicat pour afficher le mot de passe de la base de données MongoDB Méthode de Navicat pour afficher le mot de passe de la base de données MongoDB Apr 08, 2025 pm 09:39 PM

Il est impossible de visualiser le mot de passe MongoDB directement via NAVICAT car il est stocké sous forme de valeurs de hachage. Comment récupérer les mots de passe perdus: 1. Réinitialiser les mots de passe; 2. Vérifiez les fichiers de configuration (peut contenir des valeurs de hachage); 3. Vérifiez les codes (May Code Hardcode).

See all articles