咱們使用 pecl 命令來安裝:php
/usr/local/php7/bin/pecl install mongodb
執行成功後,會輸出如下結果: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 配置。數據庫
能夠直接執行如下命令來添加。php7
echo "extension=mongodb.so" >> `/usr/local/php7/bin/php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
注意:以上執行的命令中 php7 的安裝目錄爲 /usr/local/php7/,若是你安裝在其餘目錄,須要相應修改 pecl 與 php 命令的路徑。ui
PHP7 鏈接 MongoDB 語法以下:google
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
將 name 爲"baidu" 的數據插入到 test 數據庫的 runoob 集合中。url
<?php $bulk = new MongoDB\Driver\BulkWrite; $document = ['_id' => new MongoDB\BSON\ObjectID, 'name' => 'baidu']; $_id= $bulk->insert($document); var_dump($_id); $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); $result = $manager->executeBulkWrite('test.runoob', $bulk, $writeConcern); ?>
這裏咱們將三個網址數據插入到 test 數據庫的 sites 集合,並讀取迭代出來:spa
<?php $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017"); // 插入數據 $bulk = new MongoDB\Driver\BulkWrite; $bulk->insert(['x' => 1, 'name'=>'Baidu', 'url' => 'http://www.baidu.com']); $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); } ?>
輸出結果爲:.net
stdClass Object ( [x] => 3 [name] => taobao [url] => http://www.taobao.com ) stdClass Object ( [x] => 2 [name] => Google [url] => http://www.google.com )