發現 MongoDB 是好一陣子前的事,而我也在某台機器上把它裝起來。
之前玩的時候,發現 MongoDB 不須帳號與密碼就可以連接,而且也無法配置使用者權限,所以把它丟在旁邊。
前幾天,我在網路上看到網友詢問 MongoDB 有沒有辦法作 JOIN,而他得到的答案是否定的。
趁著今天在家閒閒沒事作,書也看完幾個段落,就透過 PHP 來試試這種 ODBMS 如何實作資料關聯。
MongoDB 與常見的資料庫(例如:MySQL)有些微的不同:
資料庫 | 資料表 | |
MongoDB 稱之為 | Database(DB) | Collection |
MySQL 稱之為 | Database(DB) | Table |
先把這個觀念講清楚,底下的範例程式碼才不會看得霧煞煞。
首先,先建立 DB 與 Collection:
// 連接 MongoDB $m = new Mongo(); // 連接資料庫,名稱就是 test $testDB = $m->selectDB( 'test' ); // 建立 Collection,名稱分別是 user 與 sex $testDB->createCollection( 'user' ); $testDB->createCollection( 'sex' );
- MongoDB 沒有 createDB 這種指令。只要選擇資料庫,建立 Collection 之後,系統就會自動產生 DB。
- 指令列模式下,選擇資料庫的指令跟 MySQL 相同(USE DB_NAME)。
再來,存入性別資料:
// 連接 MongoDB $m = new Mongo(); // 連接資料庫,名稱就是 test $testDB = $m->selectDB( 'test' ); // 在 sex 這個 Collection 裡面放入資料,好讓程式分辨男性與女性 $testDB->sex->insert( array('sex_name' => 'Female') ); $testDB->sex->insert( array('sex_name' => 'Male') ); // 把 sex 這個 Collection 的資料倒出來看 $cursor = $testDB->sex->find(); $array = iterator_to_array($cursor); var_dump($array);
- 以往我們儲存在 Table 的 data row 會有個 id 值,方便我們建立關聯。MongoDB 這種資料庫則是在 Collection 裡面放物件,可以不需要 id 值。
開始存入使用者名稱,並紀錄他(她)們的性別:
// 連接 MongoDB $m = new Mongo(); // 連接資料庫,名稱就是 test $testDB = $m->selectDB( 'test' ); // 找出男性資料,並取得關聯值 $male = $testDB->sex->findOne( array('sex_name' => 'Male') ); $refMale = $testDB->sex->createDBRef( $male ); // 找出女性資料,並取得關聯值 $female = $testDB->sex->findOne( array('sex_name' => 'Female') ); $refFemale = $testDB->sex->createDBRef( $female ); // 存入使用者資料 $testDB->user->insert( array('name' => 'BoyName', 'sex' => $refMale) ); $testDB->user->insert( array('name' => 'GirlName', 'sex' => $refFemale) ); // 取出並顯示使用者資料 $cursor = $testDB->user->find(); $array = iterator_to_array($cursor); foreach ( $array as $user ) { // 找出性別的關聯物件 $sexRef = $testDB->user->getDBRef($user['sex']); echo "Name: {$user['name']}\tSex: {$sexRef['sex_name']}\n"; }
以上,簡單的試玩心得。