Complete example explanation of mongoDB database operation class implemented in PHP

jacklove
Release: 2023-04-01 20:46:01
Original
1630 people have browsed it

This article mainly introduces the mongoDB database operation class implemented by PHP. It combines the complete example form with a detailed analysis of PHP's implementation skills for mongoDB database connection, addition, deletion, modification, statistics and other operations based on the singleton mode. Friends in need can refer to it. Next

The example of this article describes the mongoDB database operation class implemented by PHP. Share it with everyone for your reference, the details are as follows:

The database used in the recent project development is the mongodb database. Because the editor's company has just used the mongodb database, there is no encapsulated mongodb database operation class before. To use it, so I encapsulated a mongodb database operation class in the project and shared it here. I hope you won’t criticize the unsatisfactory parts.

As we all know, mongodb is a typical representative of nosql database and is sought after by many developers. It has been particularly popular in recent years. The popularity of mongodb is not without reason. Let me give you a brief introduction to MongoDB.

MongoDB is a product between a relational database and a non-relational database. It is the most feature-rich among non-relational databases and is most like a relational database. The data structure it supports is very loose and is a json-like bjson format, so it can store more complex data types. The biggest feature of Mongo is that the query language it supports is very powerful. Its syntax is somewhat similar to an object-oriented query language. It can almost implement most functions similar to single-table queries in relational databases, and it also supports indexing of data.

It is characterized by high performance, easy deployment, easy use, and very convenient for storing data. The main functional features are:

Oriented to collection storage, easy to store object type data.
Free mode.
Support dynamic query.
Supports full indexing, including internal objects.
Support query.
Supports replication and failure recovery.
Use efficient binary data storage, including large objects (such as videos, etc.).
Automatically handle fragmentation to support cloud computing level scalability
Supports RUBY, PYTHON, JAVA, C, PHP and other languages.
The file storage format is BSON (an extension of JSON)
Can be accessed through the network

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

Schema-free means that for files stored in the mongodb database, we do not need to know any structure definition of it. If necessary, you can store files with different structures in the same database.

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

The MongoDB server can run on Linux, Windows or OS X platforms, supports 32-bit and 64-bit applications, and the default port is 27017. It is recommended to run on a 64-bit platform because the maximum file size supported by MongoDB

is 2GB when running in 32-bit mode.

MongoDB stores data in files (the default path is: /data/db) and uses memory-mapped files for management to improve efficiency.

The database operation class source code of the PHP operation MongoDB database encapsulated by the editor is as follows, for reference only.

<?php
/**
 * PHP操作mongodb数据库操作类
 */
class Database {
  protected $database  = &#39;&#39;;
  protected $mo;
  /**
   * 构造方法
   */
  public function __construct() {
    $server = DBSERVER;
    $user = DBUSER;
    $password = DBPASS;
    $port = DBPORT;
    $database = DBNAME;
    $mongo = $this->getInstance($server, $user, $password, $port);
    $this->database = $mongo->$database;
  }
  /**
   * 数据库单例方法
   * @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;
    }
  }
  /**
   * 查询表中所有数据
   * @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 = &#39;&#39;, $skip = &#39;&#39;) {
    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;
  }
  /**
   * 查询指定一条数据
   * @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;
  }
  /**
   * 统计个数
   * @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;
  }
  /**
   * 直接执行mongo命令
   * @param $sql
   * @return array
   */
  public function toExcute($sql) {
    $result = $this->database->execute($sql);
    return $result;
  }
  /**
   * 分组统计个数
   * @param $table
   * @param $where
   * @param $field
   */
  public function groupCount($table, $where, $field) {
    $cond = array(
      array(
        &#39;$match&#39; => $where,
      ),
      array(
        &#39;$group&#39; => array(
          &#39;_id&#39; => &#39;$&#39; . $field,
          &#39;count&#39; => array(&#39;$sum&#39; => 1),
        ),
      ),
      array(
        &#39;$sort&#39; => array("count" => -1),
      ),
    );
    $this->database->$table->aggregate($cond);
  }
  /**
   * 删除数据
   * @param $table
   * @param $where
   * @return array|bool
   */
  public function toDelete($table, $where) {
    $re = $this->database->$table->remove($where);
    return $re;
  }
  /**
   * 插入数据
   * @param $table
   * @param $data
   * @return array|bool
   */
  public function toInsert($table, $data) {
    $re = $this->database->$table->insert($data);
    return $re;
  }
  /**
   * 更新数据
   * @param $table
   * @param $where
   * @param $data
   * @return bool
   */
  public function toUpdate($table, $where, $data) {
    $re = $this->database->$table->update($where, array(&#39;$set&#39; => $data));
    return $re;
  }
  /**
   * 获取唯一数据
   * @param $table
   * @param $key
   * @return array
   */
  public function distinctData($table, $key, $query = array()) {
    if (!empty($query)) {
      $where = array(&#39;distinct&#39; => $table, &#39;key&#39; => $key, &#39;query&#39; => $query);
    } else {
      $where = array(&#39;distinct&#39; => $table, &#39;key&#39; => $key);
    }
    $data = $this->database->command($where);
    return $data[&#39;values&#39;];
  }
}
?>
Copy after login

Articles you may be interested in:

ThinkPHP framework uses redirect to implement page redirection Method example explanation

#php Multiple methods to explain whether the string contains the specified string

php framework CodeIgniter Explain the method of using redis

The above is the detailed content of Complete example explanation of mongoDB database operation class implemented in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!