Home  >  Article  >  Backend Development  >  Detailed explanation of PHP+mongoDB database operation steps

Detailed explanation of PHP+mongoDB database operation steps

php中世界最好的语言
php中世界最好的语言Original
2018-05-16 16:31:191964browse

This time I will bring you PHP mongoDBDatabase operationdetailed steps, what are the notes of PHP mongoDB database, the following is a practical case, let's take a look.

The database used in the recent project development is the mongodb database. Because my company has just used the mongodb database, there was no encapsulated mongodb database operation class for use before, so I used it myself in the project. It encapsulates a mongodb database operation class, and I would like to share it with you. 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 the object-oriented query language. It can almost achieve most functions similar to single-table queries in relational databases, and it also supports data processing. Create an index.

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). The difference is 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.

<?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;];
  }
}
?>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

php WeChat official account randomly distributes cash red envelopes

PHP realizes session sharing under load balancing Detailed explanation of the case (with code)

The above is the detailed content of Detailed explanation of PHP+mongoDB database operation steps. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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