环境说明
-
php7
-
centos7
-
mongodb4.0.5
默认情况下,php并没有安装mongodb
扩展,会报Class 'MongoDB\Driver\Query' not found
错误。
pecl安装扩展
通过pecl
可以很方便地安装扩展
注意:如果安装了多个版本的php,需要进行相应版本的pecl
目录,如:
➜ bin pwd
/usr/local/php7.1/bin
➜ bin sudo ./pecl install mongodb
安装完成后,在php.ini
添加:extension=mongodb.so
重启php, 查看 phpinfo
image测试
<?php $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// 插入数据
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['id' => 1, 'name'=>'Google']);
$bulk->insert(['id' => 2, 'name'=>'Github']);
$bulk->insert(['id' => 3, 'name'=>'StackOverFlow']);
$manager->executeBulkWrite('test.sites', $bulk);
$filter = ['id' => ['$gt' => 1]];
$options = [
'projection' => ['_id' => 0],
'sort' => ['id' => -1],
];
// 查询数据
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('test.sites', $query);
foreach ($cursor as $document) {
echo "<pre>";
var_dump($document);
}
执行结果:
image
网友评论