关于升级PHP7操作MongoDB-PHP7

资源魔 38 0
媒介

应用 PHP+MongoDB 的用户不少,由于 MongoDB 对非构造化数据的存储很不便。正在 PHP5 及之前,民间提供了两个扩大,Mongo 以及 MongoDB,此中 Mongo 是对以 MongoClient 等几个外围类为根底的类群进行操作,封装患上很不便,以是根本上城市抉择 Mongo 扩大。

概况请见民间手册:https://www.php.net/manual/zh/book.mongo.php

然而跟着 PHP5 晋级到 PHP7,民间再也不支持 Mongo 扩大,只支持 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 驱动

假如应用原驱动的话,大抵语法以下:

<?php
use MongoDB\Driver\Manager;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\WriteConcern;
use MongoDB\Driver\Query;
use MongoDB\Driver\Co妹妹and;
class MongoDb {
    protected $mongodb;
    protected $database;
    protected $collection;
    protected $bulk;
    protected $writeConcern;
    protected $defaultConfig
        = [
            'hostname' => 'localhost',
            'port' => '27017',
            'username' => '',
            'password' => '',
            'database' => 'test'
        ];
    public function __construct($config) {
        $config = array_merge($this->defaultConfig, $config);
        $mongoServer = "mongodb://";
        if ($config['username']) {
            $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
        }
        $mongoServer .= $config['hostname'];
        if ($config['port']) {
            $mongoServer .= ':' . $config['port'];
        }
        $mongoServer .= '/' . $config['database'];
        $this->mongodb = new Manager($mongoServer);
        $this->database = $config['database'];
        $this->collection = $config['collection'];
        $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 = []) {
        $co妹妹and = new Co妹妹and(['count' => $this->collection, 'query' => $where]);
        $result = $this->mongodb->executeCo妹妹and($this->database, $co妹妹and);
        $res = $result->toArray();
        $count = 0;
        if ($res) {
            $count = $res[0]->n;
        }
        return $count;
    }
    public function update($where = [], $update = [], $upsert = false) {
        $this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $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, ['limit' => $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, [
    '$set' => $values
,[
    'multiple' => true//多条,单条false
]);

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

4.查问

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

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

5.删除了

$collention->remove($condition, [
    'justOne' => false//删单条
]);
$collention->remove([]);//删一切

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

增补

有些人可能习气以相似 MySQL 的自增 ID 来解决数据,之前可能应用 findAndModify() 办法来查问并修正:

$collention->findAndModify([
    '_id' => $tableName//我正在自增表顶用其它的表名作主键
], [
    '$inc' => ['id' => 1]//自增
], [
    '_id' => 0
], [
    'new' => 1//前往修正后的后果,默许是修正前的
]);

如今应用 MongoDB 库的话需求修正为:

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

相似的另有 findOneAndDelete() findOneAndReplace(),更多内容可见文档

以上就是对于晋级PHP7操作MongoDB的具体内容,更多请存眷资源魔其它相干文章!

标签: PHP7 php7开发教程 php7开发资料 php7开发自学

抱歉,评论功能暂时关闭!