本文基於舊版 mongodb/mongodb (PHP Library) 或 ext-mongo (legacy) 的常見用法整理。新專案請使用官方 mongodb/mongodb Composer 套件 (PHP 7.1+),底層依賴 ext-mongodb 擴展。以下提供核心 API 速查與實用範例。
# 安裝擴展 (PECL)
pecl install mongodb
# Composer 專案
composer require mongodb/mongodb
php.ini 加入 extension=mongodb.so (或 php_mongodb.dll)。
selectDatabase('myapp'); // $client->myapp
$collection = $db->selectCollection('users'); // $db->users
insertOne([
'name' => 'Wang Wu',
'age' => 25,
'tags' => ['php', 'mongodb'],
'created_at' => new MongoDB\BSON\UTCDateTime(),
]);
echo "Inserted ID: " . $insertOneResult->getInsertedId();
// 批次
$insertManyResult = $collection->insertMany([
['name' => 'Li Si', 'age' => 30],
['name' => 'Zhang San', 'age' => 28],
]);
echo "Inserted IDs: " . json_encode($insertManyResult->getInsertedIds());
findOne(['name' => 'Wang Wu']);
// 查多筆 (游標)
$cursor = $collection->find(
['age' => ['$gte' => 20, '$lte' => 30]], // 條件
['projection' => ['name' => 1, 'age' => 1], 'sort' => ['age' => -1], 'limit' => 10]
);
foreach ($cursor as $doc) {
print_r($doc);
}
// 計數
$count = $collection->countDocuments(['status' => 1]);
updateOne(
['_id' => $id],
['$set' => ['age' => 26, 'updated_at' => new MongoDB\BSON\UTCDateTime()]]
);
// $inc: 數值增減
$collection->updateOne(['_id' => $id], ['$inc' => ['login_count' => 1]]);
// $push / $addToSet: 陣列操作
$collection->updateOne(['_id' => $id], ['$push' => ['tags' => 'new-tag']]);
$collection->updateOne(['_id' => $id], ['$addToSet' => ['tags' => 'unique-tag']]); // 不重複
// $pull: 移除陣列元素
$collection->updateOne(['_id' => $id], ['$pull' => ['tags' => 'old-tag']]);
// 批次更新
$collection->updateMany(
['status' => 1],
['$set' => ['last_sync' => new MongoDB\BSON\UTCDateTime()]]
);
// 替換整份文件 (慎用)
$collection->replaceOne(['_id' => $id], $newDocument);
deleteOne(['_id' => $id]);
$collection->deleteMany(['status' => 0]); // 批次刪除
| 類別 | 運算子 | 範例 |
|---|---|---|
| 比較 | $eq | ['age' => ['$eq' => 25]] |
$gt / $gte | ['age' => ['$gt' => 18]] | |
$lt / $lte | ['price' => ['$lte' => 100]] | |
$in | ['status' => ['$in' => [1,2]]] | |
$nin | ['tags' => ['$nin' => ['spam']]] | |
| 邏輯 | $and | ['$and' => [['a'=>1], ['b'=>2]]] |
$or | ['$or' => [['x'=>1], ['y'=>2]]] | |
$not | ['age' => ['$not' => ['$gt' => 60]]] | |
| 陣列 | $all | ['tags' => ['$all' => ['php','mongodb']]] |
$elemMatch | ['scores' => ['$elemMatch' => ['$gt' => 80]]] | |
$size | ['tags' => ['$size' => 3]] | |
| 元素 | $exists | ['email' => ['$exists' => true]] |
createIndex(['email' => 1], ['unique' => true]);
// 複合索引 (查詢順序需符合前綴)
$collection->createIndex(['status' => 1, 'created_at' => -1]);
// 文字索引 (全文搜尋)
$collection->createIndex(['title' => 'text', 'content' => 'text']);
// 使用: $collection->find(['$text' => ['$search' => 'mongodb php']]);
| 特性 | legacy ext-mongo (php_mongo.dll) | 新 mongodb/mongodb (ext-mongodb) |
|---|---|---|
| PHP 版本 | ≤ 5.6 (已停止維護) | 7.1+ (現行主流) |
| 類別名 | MongoClient, MongoCollection | MongoDB\Client, MongoDB\Collection |
| ID 類型 | MongoId | MongoDB\BSON\ObjectId |
| 日期類型 | MongoDate | MongoDB\BSON\UTCDateTime |
| 更新語法 | update($cond, $data) | updateOne($cond, ['$set' => $data]) |
強烈建議: 所有新專案直接使用 mongodb/mongodb,舊專案規劃遷移。