PHP7 MongoDB 安裝與使用
阿新 • • 發佈:2018-12-24
PHP7 Mongdb 擴充套件安裝
我們使用 pecl 命令來安裝:
$ /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"isnotset to php.ini locationYou 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 命令的路徑。
Mongodb 使用
PHP7 連線 MongoDB 語法如下:
$manager =newMongoDB\Driver\Manager("mongodb://localhost:27017");
插入資料
將 name 為"自學教程" 的資料插入到 test 資料庫的 runoob 集合中。
<?php $bulk = new MongoDB\Driver\BulkWrite; $document = ['_id' => new MongoDB\BSON\ObjectID, 'name' => '菜鳥教程']; $_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); ?>
讀取資料
<?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);
}
?>
更新資料
<?php
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
['x' => 2],
['$set' => ['name' => '菜鳥工具', 'url' => 'tool.runoob.com']],
['multi' => false, 'upsert' => false]
);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.sites', $bulk, $writeConcern);
?>
刪除資料
<?php
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['x' => 1], ['limit' => 1]); // limit 為 1 時,刪除第一條匹配資料
$bulk->delete(['x' => 2], ['limit' => 0]); // limit 為 0 時,刪除所有匹配資料
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.sites', $bulk, $writeConcern);
?>