Home  >  Article  >  Backend Development  >  About upgrading PHP7 to operate MongoDB

About upgrading PHP7 to operate MongoDB

藏色散人
藏色散人forward
2020-04-18 13:22:052825browse

Preface

There are many users using PHP MongoDB because MongoDB is very convenient for storing unstructured data. In PHP5 and before, two official extensions were provided, Mongo and MongoDB. Mongo operates on categories based on several core classes such as MongoClient. It is very convenient to encapsulate, so Mongo extensions are basically chosen.

For details, please see the official manual: https://www.php.net/manual/zh/book.mongo.php

However, with the upgrade from PHP5 to PHP7, Mongo is no longer officially supported. Extension only supports MongoDB, and the performance improvement of PHP7 is huge, which makes people unable to give up, so how to replace Mongo with MongoDB has become an urgent problem to be solved. MongoDB introduces namespaces, but the functional encapsulation is very poor. If you have to use native extensions, it almost means writing native Mongo statements. This idea goes against the idea of ​​ORM simplifying the syntax problems caused by DB IO operations and focusing on logic optimization.

For details, please also refer to the official manual: https://www.php.net/manual/zh/set.mongodb.php

Under this situation, MongoDB officials could not help but In order to facilitate use and increase market share, a library based on MongoDB extension has been launched: https://github.com/mongodb/mongo-php-library

For detailed documentation of this library, please see: https:/ /docs.mongodb.com/php-library/current/reference/

MongoDB driver

If you use the original driver, the approximate syntax is as follows:

<?php
use MongoDB\Driver\Manager;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\WriteConcern;
use MongoDB\Driver\Query;
use MongoDB\Driver\Command;
class MongoDb {
    protected $mongodb;
    protected $database;
    protected $collection;
    protected $bulk;
    protected $writeConcern;
    protected $defaultConfig
        = [
            &#39;hostname&#39; => &#39;localhost&#39;,
            &#39;port&#39; => &#39;27017&#39;,
            &#39;username&#39; => &#39;&#39;,
            &#39;password&#39; => &#39;&#39;,
            &#39;database&#39; => &#39;test&#39;
        ];
    public function __construct($config) {
        $config = array_merge($this->defaultConfig, $config);
        $mongoServer = "mongodb://";
        if ($config[&#39;username&#39;]) {
            $mongoServer .= $config[&#39;username&#39;] . &#39;:&#39; . $config[&#39;password&#39;] . &#39;@&#39;;
        }
        $mongoServer .= $config[&#39;hostname&#39;];
        if ($config[&#39;port&#39;]) {
            $mongoServer .= &#39;:&#39; . $config[&#39;port&#39;];
        }
        $mongoServer .= &#39;/&#39; . $config[&#39;database&#39;];
        $this->mongodb = new Manager($mongoServer);
        $this->database = $config[&#39;database&#39;];
        $this->collection = $config[&#39;collection&#39;];
        $this->bulk = new BulkWrite();
        $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
    }
    public function query($where = [], $option = []) {
        $query = new Query($where, $option);
        $result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
        return json_encode($result);
    }
    public function count($where = []) {
        $command = new Command([&#39;count&#39; => $this->collection, &#39;query&#39; => $where]);
        $result = $this->mongodb->executeCommand($this->database, $command);
        $res = $result->toArray();
        $count = 0;
        if ($res) {
            $count = $res[0]->n;
        }
        return $count;
    }
    public function update($where = [], $update = [], $upsert = false) {
        $this->bulk->update($where, [&#39;$set&#39; => $update], [&#39;multi&#39; => true, &#39;upsert&#39; => $upsert]);
        $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
        return $result->getModifiedCount();
    }
    public function insert($data = []) {
        $this->bulk->insert($data);
        $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
        return $result->getInsertedCount();
    }
    public function delete($where = [], $limit = 1) {
        $this->bulk->delete($where, [&#39;limit&#39; => $limit]);
        $result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
        return $result->getDeletedCount();
    }
}

This syntax is too different from before and it is inconvenient to change. Change to PHP MongoDB library

MongoDB library

1. Connection

Original

new MongoClient();

New

new MongoDB\Client();

2.New

Original

$collention->insert($array, $options);

New

$resultOne = $collention->insertOne($array, $options);//单
$lastId = $resultOne->getInsertedId();
$resultMany = $collention->insertMany($array, $options);//多
$count = $resultMany->getInsertedCount();

3.Modify

Original

$collention->update($condition, [
    &#39;$set&#39; => $values
,[
    &#39;multiple&#39; => true//多条,单条false
]);

New

$collection->updateOne(
    [&#39;state&#39; => &#39;ny&#39;],
    [&#39;$set&#39; => [&#39;country&#39; => &#39;us&#39;]]
);
$updateResult = $collection->updateMany(
    [&#39;state&#39; => &#39;ny&#39;],
    [&#39;$set&#39; => [&#39;country&#39; => &#39;us&#39;]]
);
$count = $updateResult->getModifiedCount();

4.Query

$cursor = $collection->find($condition, [
    &#39;name&#39; => true//指定字段
]);
$cursor->skip(5);
$cursor->limit(5);
$cursor->sort([
    &#39;time&#39; => -1
]);

$cursor = $collection->find($condition, [
    &#39;skip&#39; => 5,
    &#39;limit&#39; => 5,
    &#39;sort&#39; => [
        &#39;time&#39; => -1
    ],//排序
    &#39;projection&#39; => [
        &#39;name&#39; => 1//指定字段
    ]
]);

5. Delete

$collention->remove($condition, [
    &#39;justOne&#39; => false//删单条
]);
$collention->remove([]);//删所有

$result = $collention->deleteOne($condition, $options);
$collention->deleteMany($condition, $options);
$result->getDeletedCount();

Supplement

Some people may be used to processing data with auto-increment IDs similar to MySQL. In the past, they may have used the findAndModify() method to query and modify:

$collention->findAndModify([
    &#39;_id&#39; => $tableName//我在自增表中用其它的表名作主键
], [
    &#39;$inc&#39; => [&#39;id&#39; => 1]//自增
], [
    &#39;_id&#39; => 0
], [
    &#39;new&#39; => 1//返回修改后的结果,默认是修改前的
]);

Now use the MongoDB library Needs to be modified to:

$collention->findOneAndUpdate([
    &#39;_id&#39; => $tableName
], [
    &#39;$inc&#39; => [&#39;id&#39; => 1]
], [
    &#39;projection&#39; => [&#39;id&#39; => 1],
    &#39;returnDocument&#39; => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
]);

Similarly, there is findOneAndDelete() findOneAndReplace(). For more information, please seeDocumentation

The above is the detailed content of About upgrading PHP7 to operate MongoDB. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete