PHP Driver- PHPLIB
2017-08-01 本文已影响0人
我是大彬子
最近在折腾MongoDB,在用PHP连接过程中发现诸多问题,最后选择用了PHPLIB,也写下来心酸历程,以便查阅。首先在MongoDB的文档中查阅到,PHP有3个驱动(吐槽下,为啥要弄三个!选择恐惧症有没有)。也贴出官网的图片,有需要的可以点击查阅
- mongo(已经被废弃,不支持PHP7,使用mongodb)
- mongodb
- phplib

mongodb
安装很简单,可以使用pecl安装后即可使用
# pecl install mongodb
使用过之后总体感觉这个驱动过于复杂,并且没有找到aggregation操作(有可能也是自己不会用,如果有请指教)。所以改用了PHPLIB
PHPLIB
安装
由于PHPLIB是基于MongoDB驱动的,所以首先需要安装MongoDB驱动
# pecl install mongodb
修改过PHP.INI后,使用Composer安装PHPLIB
composer require mongodb/mongodb
到这里PHPLIB已经安装成功!
CURD(来源)
include ('vendor/autoload.php');
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;
// insert
$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
echo "Inserted with Object ID '{$result->getInsertedId()}'";
# Inserted with Object ID '598024bbe13823699e7a9652'
// query
$result = $collection->find(['name' => 'Hinterland', 'brewery' => 'BrewDog']);
foreach($result as $entry){
echo $entry['_id'], ': ', $entry['name'], "\n";
}
# 598024bbe13823699e7a9652: Hinterland
//update
$result = $collection->updateOne(['name' => 'Hinterland'],
['$set' => ['job' => 'developer']]);
MongoDB Enterprise > db.beers.find().pretty();
{
"_id" : ObjectId("598024bbe13823699e7a9652"),
"name" : "Hinterland",
"brewery" : "BrewDog",
"job" : "developer"
}
// delete
$result = $collection->deleteOne(['name' => 'Hinterland']);
echo $result->getDeletedCount();
PHPLIB试用感觉比MongoDB方便一些,借助IDE提示基本上可以不看文档即可开发。再次吐槽官网MongoDB API!!