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 = [ '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 = []) { $command = new Command(['count' => $this->collection, 'query' => $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, ['$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(); } }
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, [ '$set' => $values ,[ 'multiple' => true//多条,单条false ]);
New
$collection->updateOne( ['state' => 'ny'], ['$set' => ['country' => 'us']] ); $updateResult = $collection->updateMany( ['state' => 'ny'], ['$set' => ['country' => 'us']] ); $count = $updateResult->getModifiedCount();
4.Query
老
$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. Delete
老
$collention->remove($condition, [ 'justOne' => 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([ '_id' => $tableName//我在自增表中用其它的表名作主键 ], [ '$inc' => ['id' => 1]//自增 ], [ '_id' => 0 ], [ 'new' => 1//返回修改后的结果,默认是修改前的 ]);
Now use the MongoDB library Needs to be modified to:
$collention->findOneAndUpdate([ '_id' => $tableName ], [ '$inc' => ['id' => 1] ], [ 'projection' => ['id' => 1], 'returnDocument' => 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!

在php5中,我们可以使用fsockopen()函数来检测TCP端口。这个函数可以用来打开一个网络连接和进行一些网络通信。但是在php7中,fsockopen()函数可能会遇到一些问题,例如无法打开端口、无法连接到服务器等。为了解决这个问题,我们可以使用socket_create()函数和socket_connect()函数来检测TCP端口。

php7.0安装mongo扩展的方法:1、创建mongodb用户组和用户;2、下载mongodb源码包,并将源码包放到“/usr/local/src/”目录下;3、进入“src/”目录;4、解压源码包;5、创建mongodb文件目录;6、将文件复制到“mongodb/”目录;7、创建mongodb配置文件并修改配置即可。

解决 PHP 7.0 中插件未显示已安装问题的方法:检查插件配置并启用插件。重新启动 PHP 以应用配置更改。检查插件文件权限,确保其正确。安装丢失的依赖项,以确保插件正常运行。如果其他步骤均失败,则重建 PHP。其他可能原因包括插件版本不兼容、加载错误版本或 PHP 配置问题。

PHP8相较于PHP7在性能、新特性和语法改进、类型系统、错误处理和扩展等方面都有一些优势和改进。然而,选择使用哪个版本要根据具体的需求和项目情况来决定。详细介绍:1、性能提升,PHP8引入了Just-in-Time(JIT)编译器,可以提高代码的执行速度;2、新特性和语法改进,PHP8支持命名参数和可选参数的声明,使得函数调用更加灵活;引入了匿名类、属性的类型声明等等。

PHP服务器环境常见的解决方法包括:确保已安装正确的PHP版本和已复制相关文件到模块目录。临时或永久禁用SELinux。检查并配置PHP.ini,确保已添加必要的扩展和进行正确设置。启动或重启PHP-FPM服务。检查DNS设置是否存在解析问题。

php7.0安装部署的方法:1、到PHP官网下载与本机系统对应的安装版本;2、将下载的zip文件解压到指定目录;3、打开命令行窗口,在“E:\php7”目录下运行“php -v”命令即可。

随着互联网技术的发展,计算机编程语言也随之不断发展和更新。PHP作为一种广泛应用于Web开发领域的编程语言,在多年的发展中经历了多个版本的更新,而最新版的PHP7又在性能和稳定性上有了巨大提升。为了能更好地应用PHP编程语言,这篇文章将介绍PHP7的下载和安装教程,供初学者参考。

本地环境:redhat6.7系统。nginx1.12.1,php7.1.0,代码使用yii2框架问题:本地的web站需要用到elasticsearch服务。当php使用本地服务器搭建的elasticsearch时,本地的负载都是正常。当我使用aws的elasticsearchservice服务时,本地服务器出现负载经常过高的情况。查看nginx和php日志,发现没有异常。系统的并发连接数也不高。这时候想到我们老大给我讲的一个strace诊断工具。调试过程:查找一个php的子进程idstrace-


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
