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!