>  기사  >  백엔드 개발  >  MongoDB를 작동하기 위한 PHP7 업그레이드 정보

MongoDB를 작동하기 위한 PHP7 업그레이드 정보

藏色散人
藏色散人앞으로
2020-04-18 13:22:052753검색

머리말

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 문을 작성하는 것을 의미합니다. 이 아이디어는 DB IO 작업으로 인해 발생하는 구문 문제를 단순화하고 논리 최적화에 초점을 맞춘 ORM의 아이디어와 반대됩니다.

자세한 내용은 공식 매뉴얼도 참고해주세요: 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\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.

Original

new MongoClient();

New

new MongoDB\Client();

2.Add

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. E

$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//指定字段
    ]
]);

삭제

Rha

$collention->remove($condition, [
    &#39;justOne&#39; => false//删单条
]);
$collention->remove([]);//删所有
신규
$result = $collention->deleteOne($condition, $options);
$collention->deleteMany($condition, $options);
$result->getDeletedCount();

보충

일부 사람들은 다음을 사용하여 데이터를 처리하는 데 익숙해질 수 있습니다. MySQL과 같은 자체 증분 ID() 쿼리 및 수정 방법:

$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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제