当前位置: 首页 > 后端技术 > PHP

升级PHP7操作MongoDB

时间:2023-03-29 18:45:50 PHP

前言使用PHP+MongoDB的用户很多,因为MongoDB存储非结构化数据非常方便。在PHP5之前,官方提供了两个扩展,Mongo和MongoDB。其中,Mongo基于MongoClient等几个核心类对组进行操作。封装起来很方便,所以基本选择了Mongo扩展。具体可以参考官方手册:http://php.net/manual/zh/book...但是随着PHP5升级到PHP7,官方不再支持Mongo扩展,只支持MongoDB,而且PHP7的性能有了很大的提升,让人无法放弃,所以如何用MongoDB替代Mongo成为了一个亟待解决的问题。MongoDB引入了命名空间,但是功能封装很差。如果你必须使用原生扩展,那几乎意味着编写原生的Mongo语句。这种思路与ORM简化DBIO操作带来的语法问题,侧重于逻辑优化的思路背道而驰。具体可以参考官方手册:http://php.net/manual/zh/set....这种情况下,MongoDB官方也没办法了。为了方便使用和提高市场占有率,推出了MongoDB扩展库:https://github.com/mongodb/mo...库的详细文档参见:https://docs.mongodb.com/php-...如果MongoDB驱动使用原版驱动,大致语法如下:;使用MongoDB\Driver\Command;classMongoDb{protected$mongodb;受保护的$database受保护的$collection;受保护的$散装;受保护的$writeConcern;protected$defaultConfig=['hostname'=>'localhost','port'=>'27017','username'=>'','password'=>'','database'=>'test'];公共函数__construct($config){$config=array_merge($this->defaultConfig,$config);$mongoServer="mongodb://";如果($config['用户名']){$mongoServer.=$config['用户名'].':'。$config['密码'].'@';}$mongoServer.=$config['主机名'];如果($config['port']){$mongoServer.=':'.$配置['端口'];$mongoServer.='/'。$config['数据库'];$this->mongodb=newManager($mongoServer);$this->database=$config['数据库'];$this->collection=$config['collection'];$this->bulk=newBulkWrite();$this->writeConcern=newWriteConcern(WriteConcern::MAJORITY,100);}publicfunctionquery($where=[],$option=[]){$query=newQuery($where,$option);$result=$this->mongodb->e??xecuteQuery("$this->database.$this->collection",$query);返回json_encode($result);}publicfunctioncount($where=[]){$command=newCommand(['count'=>$this->collection,'query'=>$where]);$result=$this->mongodb->e??xecuteCommand($this->database,$command);$res=$结果->toArray();$计数=0;如果($res){$count=$res[0]->n;}返回$count;}publicfunctionupdate($where=[],$update=[],$upsert=false){$this->bulk->update($where,['$set'=>$update],['multi'=>真,'upsert'=>$upsert]);$result=$this->mongodb->e??xecuteBulkWrite("$this->database.$this->collection",$this->bulk,$this->writeConcern);返回$result->getModifiedCount();}publicfunctioninsert($data=[]){$this->bulk->insert($data);$result=$this->mongodb->e??xecuteBulkWrite("$this->database.$this->collection",$this->bulk,$this->writeConcern);返回$result->getInsertedCount();}publicfunctiondelete($where=[],$limit=1){$this->bulk->delete($where,['limit'=>$limit]);$result=$this->mongodb->e??xecuteBulkWrite("$this->database.$this->collection",$this->bulk,$this->writeConcern);return$result->getDeletedCount();}}这个语法和之前的差别太大了,不方便改,改成PHPMongoDB库MongoDB库1.连接原来的newMongoClient();newnewMongoDB\Client();2.添加原来的$collention->insert($array,$options);new$resultOne=$collention->insertOne($array,$options);//单个$lastId=$resultOne->getInsertedId();$resultMany=$collention->insertMany($array,$options);//多个$count=$resultMany->getInsertedCount();3.修改原来的$collection->update($condition,['$set'=>$values,['multiple'=>true//multiple,singlefalse]);new$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(['时间'=>-1]);new$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(),更多内容见文档