# 依賴庫 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 擴展已棄用。
$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1:27017');
$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();
// 處理寫入錯誤...
}
$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 專案遷移使用。