這裡介紹如何在 PHP 中使用 MongoDB 資料庫,包含插入新增、修改更新與刪除資料等各種詳細範例教學。
MongoDB 除了基本的 MongoDB Shell 使用方式之外,它也提供了各種程式語言的 driver,以下我們介紹在 PHP 中的 MongoDB 資料庫使用方式。
以下是在 PHP 中使用 MongoDB 的範例程式碼:
<?php // MongoDB 伺服器設定 $dbhost = 'localhost'; $dbname = 'gtwang_demo'; // 連線到 MongoDB 伺服器 $mongoClient = new MongoClient('mongodb://' . $dbhost); $db = $mongoClient->$dbname; // 取得 demo 這個 collection $cDemo = $db->demo; // 要儲存的資料 $record = array( 'firstName' => 'G.T.', 'lastName' => 'Wang', 'roles' => array('developer', 'webmaster') ); // 將資料儲存至 demo 這個 collection 中 $cDemo->save($record); // 設定查詢條件 $queryCondition = array( 'firstName' => 'G.T.', 'lastName' => 'Wang' ); // 查詢資料 $result = $cDemo->findOne($queryCondition); // 輸出資料 print_r($result); ?>
輸出為
Array
(
[_id] => MongoId Object
(
[$id] => 564e8db0b2fd7fb8278b4567
)
[firstName] => G.T.
[lastName] => Wang
[roles] => Array
(
[0] => developer
[1] => webmaster
)
)
這裡用的 save 函數會依據 _id 檢查要儲存的 document 是否已經存在於 MongoDB 中,如果該 document 不存在的話,就會新增一筆,反之如果這個 document 已經存在了,就會更新該 document 資料。
如果只是單純要新增資料,可以使用 insert 函數,更新資料則可用 update 函數。
這時候我們可以使用 MongoDB Shell 連進 MongoDB 資料庫中,檢查一下資料是不是真的有儲存進去,執行:
mongo gtwang_demo
MongoDB shell version: 2.4.9 connecting to: gtwang_demo
進入 MongoDB Shell 後,查看 gtwang_demo 這個 database 中所有的 collection:
show collections
demo system.indexes
確實有出現新增的 demo collection。(在 MongoDB 中的 system.* 是系統用的 collection,不必理會它)
接著列出裡面的資料,執行:
db.demo.findOne()
{
"_id" : ObjectId("564e936bb2fd7f962e8b4567"),
"firstName" : "G.T.",
"lastName" : "Wang",
"roles" : [
"developer",
"webmaster"
]
}
看起來結果是正確的。接下來要介紹在 PHP 中 MongoDB 的一些進階查詢方法,請續閱讀下一頁。