PHP7与PHP5使用的MongoDB不一样,还在使用PHP5的是用不上
安装MongoDB拓展
pecl install mongodb
#也可以使用绝对路径
/usr/local/php7/bin/pecl install mongodb
执行成功后,会输出以下结果:
……
Build process completed successfully
Installing '/usr/local/php7/lib/php/extensions/no-debug-non-zts-20151012/mongodb.so'
install ok: channel://pecl.php.net/mongodb-1.1.7
configuration option "php_ini" is not set to php.ini location
You should add "extension=mongodb.so" to php.ini
接下来我们打开 php.ini 文件,添加 extension=mongodb.so 配置。
也可以通过指令来添加,
echo "extension=mongodb.so" >> `/usr/local/php7/bin/php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
注意:以上执行的命令中 php7 的安装目录为 /usr/local/php7/,如果你安装在其他目录,需要相应修改 pecl 与 php 命令的路径。
PHP7使用MongoDB
#连接MongoDB
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
#插入数据
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1, 'name'=>'W3Cschool教程', 'url' => 'http://www.w3cschool.cn']);
$bulk->insert(['x' => 2, 'name'=>'Google', 'url' => 'http://www.google.com']);
$bulk->insert(['x' => 3, 'name'=>'taobao', 'url' => 'http://www.taobao.com']);
$manager->executeBulkWrite('test.sites', $bulk);
$filter = ['x' => ['$gt' => 1]];
$options = [
'projection' => ['_id' => 0],
'sort' => ['x' => -1],
];
# 查询数据
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('test.sites', $query);
foreach ($cursor as $document) {
print_r($document);
}
#更新数据
$bulk->update(
['x' => 2],
['$set' => ['name' => 'w3cschool在线工具', 'url' => '123.w3cschool.cn/webtools']],
['multi' => false, 'upsert' => false]
);
#删除数据
$bulk->delete(['x' => 1], ['limit' => 1]); // limit 为 1 时,删除第一条匹配数据
$bulk->delete(['x' => 2], ['limit' => 0]); // limit 为 0 时,删除所有匹配数据
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.sites', $bulk, $writeConcern);
网友评论