ホームページ  >  記事  >  バックエンド開発  >  MongoDB を動作させるための PHP7 のアップグレードについて

MongoDB を動作させるための PHP7 のアップグレードについて

藏色散人
藏色散人転載
2020-04-18 13:22:052753ブラウズ

まえがき

MongoDB は非構造化データの保存に非常に便利なので、PHP MongoDB を使用しているユーザーがたくさんいます。 PHP5 以前では、Mongo と MongoDB という 2 つの正式な拡張機能が提供されていましたが、Mongo は MongoClient などのいくつかのコアクラスに基づいたカテゴリで動作し、カプセル化するのに非常に便利であるため、基本的に Mongo 拡張機能が選択されます。

詳細については、公式マニュアルを参照してください: https://www.php.net/manual/zh/book.mongo.php

ただし、PHP5 から PHP7 へのアップグレードでは、 Mongo は正式にサポートされなくなり、Extension では MongoDB しかサポートされず、PHP7 のパフォーマンス向上が大きく諦めきれないため、Mongo を MongoDB にどう置き換えるかが喫緊の課題となっています。 MongoDB では名前空間が導入されていますが、機能のカプセル化が非常に不十分であるため、ネイティブ拡張を使用する必要がある場合は、ネイティブの Mongo ステートメントを記述することとほぼ同じになります。この考え方は、ORM が DB IO 操作によって引き起こされる構文問題を単純化し、ロジックの最適化に重点を置くという考え方に反しています。

詳細については、公式マニュアルも参照してください: https://www.php.net/manual/zh/set.mongodb.php

この状況では、MongoDB 担当者は、次のことを行うことができませんでした。ヘルプですが、使用を容易にし、市場シェアを拡大​​するために、MongoDB 拡張機能に基づくライブラリが開始されました: https://github.com/mongodb/mongo-php-library

このライブラリの詳細なドキュメントについては、参照してください: https://docs.mongodb.com/php-library/current/reference/

MongoDB driver

元のドライバーを使用する場合、おおよその構文は次のとおりです:

<?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();
    }
}

この構文は以前と違いすぎて変更するのが不便です。PHP MongoDB ライブラリに変更します

MongoDB ライブラリ

#1.接続

元の

new MongoClient();

新しい


new MongoDB\Client();

2.新しい

元の

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

新しい

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

3.変更

元の

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

新しい

$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.クエリ

$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. 削除

##老

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

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

補足

#MySQL のような自動インクリメント ID を使用してデータを処理することに慣れている人もいるでしょう。以前は findAndModify( ) クエリと変更を行うメソッド:

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

次に MongoDB ライブラリを使用します。次のように変更する必要があります:

$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
]);

同様に、findOneAndDelete() findOneAndReplace() があります。詳細については、を参照してください# ##ドキュメンテーション######

以上がMongoDB を動作させるための PHP7 のアップグレードについての詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はsegmentfault.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。