首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 7 安裝 MongoDB 擴展與新版 API 操作指南

     編輯:PHP 綜合知識

PHP 7 環境下使用 MongoDB\Driver 新版 API

編譯安裝步驟

# 依賴庫
yum -y install openldap-devel
# 下載擴展
wget https://pecl.php.net/get/mongodb-1.1.1.tgz
# phpize
/home/server/php7/bin/phpize
./configure --with-php-config=/home/server/php7/bin/php-config
make && make install
# php.ini 加入
extension=mongodb.so

注意:PHP 7 僅支援 mongodb 擴展(對應 MongoDB 2.6+),舊版 mongo 擴展已棄用。

核心類別與操作範例

1. 建立連線管理器

$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1:27017');

2. 批量寫入

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2, 'hello' => 'world']);
$bulk->update(['_id' => 2], ['$set' => ['hello' => 'earth']]);
$bulk->insert(['_id' => 3, 'hello' => 'pluto']);
$bulk->update(['_id' => 3], ['$set' => ['hello' => 'moon']]);

$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
try {
    $result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
    echo "Inserted: {$result->getInsertedCount()}, Updated: {$result->getModifiedCount()}\n";
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    $result = $e->getWriteResult();
    // 處理寫入錯誤...
}

3. 查詢文檔

$filter = [];
$options = [
    'projection' => ['title' => 1, 'article' => 1],
    'sort' => ['views' => -1],
    'modifiers' => ['$comment' => 'query comment', '$maxTimeMS' => 100],
];
$query = new MongoDB\Driver\Query($filter, $options);
$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$cursor = $manager->executeQuery('databaseName.collectionName', $query, $readPreference);

foreach ($cursor as $doc) { var_dump($doc); }

新版 API 採用物件導向設計,效能優於舊版,建議所有 PHP 7 專案遷移使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved