Complete instance of mongoDB database operation class implemented by PHP

  • 2021-09-20 19:39:14
  • OfStack

This paper describes the mongoDB database operation class implemented by PHP. Share it for your reference, as follows:

The database used in the recent project development is mongodb database, because the company of this site is just using mongodb database, so there is no encapsulated mongodb database operation class to use before, so this site encapsulates one mongodb database operation class in the project itself, and takes it out to share it. I hope you don't spray it if you don't want it.

As we all know, mongodb is a typical representative of nosql database, which is sought after by many developers, especially in recent years. The popularity of mongodb is not without reason. Here is a brief introduction to MongoDB.

MongoDB is a product between relational database and non-relational database, which has the richest functions and is most like relational database. The data structure he supports is very loose, and it is bjson format similar to json, so it can store more complex data types. The biggest feature of Mongo is that the query language it supports is very powerful, and its syntax is somewhat similar to the object-oriented query language, which can almost realize most functions similar to the single table query of relational database, and also support indexing data.

It is characterized by high performance, easy deployment, easy use and convenient data storage. The main functional characteristics are:

Set-oriented storage, easy to store data of object type.
Mode freedom.
Support dynamic query.
Full indexing is supported, including internal objects.
Support queries.
Supports replication and failure recovery.
Use efficient binary data storage, including large objects (such as video, etc.).
Automatically handle fragmentation to support scalability at the cloud computing level
Support RUBY, PYTHON, JAVA, C + +, PHP and other languages.
The file storage format is BSON (an extension of JSON)
Accessible through the network

The so-called "set-oriented" (Collenction-Orented) means that data is stored in a data set in groups, called one set (Collenction). Each set has a unique identity name in the database and can contain an unlimited number of documents. The concept of a set is similar to that of a table (table) in a relational database (RDBMS), except that it does not need to define any schema (schema).

Schema Freedom (schema-free) means that we don't need to know any structure definitions for files stored in the mongodb database. If necessary, you can store files with different structures in the same database.

Documents stored in a collection are stored in the form of key-value pairs. The key is used to identify only one document, which is of string type, while the value can be a complex file type in each. We call this form of storage BSON (Binary Serialized dOcument Format).

MongoDB server can run on Linux, Windows or OS X platform, support 32-bit and 64-bit applications, and the default port is 27017. It is recommended to run on 64-bit platforms because MongoDB

The maximum supported file size is 2GB when running in 32-bit mode.

MongoDB stores data in a file (default path is:/data/db), which is managed using memory-mapped files for efficiency.

This site itself encapsulated PHP operation MongoDB database operation class source code as follows, for reference only.


<?php
/**
 * PHP Operation mongodb Database operation class 
 */
class Database {
  protected $database  = '';
  protected $mo;
  /**
   *  Construction method 
   */
  public function __construct() {
    $server = DBSERVER;
    $user = DBUSER;
    $password = DBPASS;
    $port = DBPORT;
    $database = DBNAME;
    $mongo = $this->getInstance($server, $user, $password, $port);
    $this->database = $mongo->$database;
  }
  /**
   *  Database singleton method 
   * @param $server
   * @param $user
   * @param $password
   * @param $port
   * @return Mongo
   */
  public function getInstance($server, $user, $password, $port) {
    if (isset($this->mo)) {
      return $this->mo;
    } else {
      if (!empty($server)) {
        if (!empty($port)) {
          if (!empty($user) && !empty($password)) {
            $this->mo = new Mongo("mongodb://{$user}:{$password}@{$server}:{$port}");
          } else {
            $this->mo = new Mongo("mongodb://{$server}:{$port}");
          }
        } else {
          $this->mo = new Mongo("mongodb://{$server}");
        }
      } else {
        $this->mo = new Mongo();
      }
      return $this->mo;
    }
  }
  /**
   *  Query all the data in the table 
   * @param $table
   * @param array $where
   * @param array $sort
   * @param string $limit
   * @param string $skip
   * @return array|int
   */
  public function getAll($table, $where = array(), $sort = array(), $limit = '', $skip = '') {
    if (!empty($where)) {
      $data = $this->database->$table->find($where);
    } else {
      $data = $this->database->$table->find();
    }
    if (!empty($sort)) {
      $data = $data->sort($sort);
    }
    if (!empty($limit)) {
      $data = $data->limit($limit);
    }
    if (!empty($skip)) {
      $data = $data->skip($skip);
    }
    $newData = array();
    while ($data->hasNext()) {
      $newData[] = $data->getNext();
    }
    if (count($newData) == 0) {
      return 0;
    }
    return $newData;
  }
  /**
   *  Query Specification 1 Bar data 
   * @param $table
   * @param array $where
   * @return int
   */
  public function getOne($table, $where = array()) {
    if (!empty($where)) {
      $data = $this->database->$table->findOne($where);
    } else {
      $data = $this->database->$table->findOne();
    }
    return $data;
  }
  /**
   *  Number of statistics 
   * @param $table
   * @param array $where
   * @return mixed
   */
  public function getCount($table, $where = array()) {
    if (!empty($where)) {
      $data = $this->database->$table->find($where)->count();
    } else {
      $data = $this->database->$table->find()->count();
    }
    return $data;
  }
  /**
   *  Direct execution mongo Command 
   * @param $sql
   * @return array
   */
  public function toExcute($sql) {
    $result = $this->database->execute($sql);
    return $result;
  }
  /**
   *  Number of grouping statistics 
   * @param $table
   * @param $where
   * @param $field
   */
  public function groupCount($table, $where, $field) {
    $cond = array(
      array(
        '$match' => $where,
      ),
      array(
        '$group' => array(
          '_id' => '$' . $field,
          'count' => array('$sum' => 1),
        ),
      ),
      array(
        '$sort' => array("count" => -1),
      ),
    );
    $this->database->$table->aggregate($cond);
  }
  /**
   *  Delete data 
   * @param $table
   * @param $where
   * @return array|bool
   */
  public function toDelete($table, $where) {
    $re = $this->database->$table->remove($where);
    return $re;
  }
  /**
   *  Insert data 
   * @param $table
   * @param $data
   * @return array|bool
   */
  public function toInsert($table, $data) {
    $re = $this->database->$table->insert($data);
    return $re;
  }
  /**
   *  Update data 
   * @param $table
   * @param $where
   * @param $data
   * @return bool
   */
  public function toUpdate($table, $where, $data) {
    $re = $this->database->$table->update($where, array('$set' => $data));
    return $re;
  }
  /**
   *  Get only 1 Data 
   * @param $table
   * @param $key
   * @return array
   */
  public function distinctData($table, $key, $query = array()) {
    if (!empty($query)) {
      $where = array('distinct' => $table, 'key' => $key, 'query' => $query);
    } else {
      $where = array('distinct' => $table, 'key' => $key);
    }
    $data = $this->database->command($where);
    return $data['values'];
  }
}
?>

For more readers interested in PHP related contents, please check the special topics of this site: "PHP+MongoDB database operation skills", "PHP database operation skills summary based on pdo", "php object-oriented programming introduction tutorial", "php string (string) usage summary", "php+mysql database operation introduction tutorial" and "php common database operation skills summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: