MongoDB 真是讓人又愛又恨,資料json化已經是大勢所趨,傳統關聯式資料庫雖然已進化到可以存json格式但統計方面還是不便,這次要做到的功能其實很簡單就是 show collections ,列出所有集合(資料表),下指令很簡單 但 php 新版的mongodb 驅動已更新,舊的語法不能用著實讓我很困擾。
本來有找到一個 php mongodb library 但版本一直對不上,只好放棄但好在該專案有上github所以就去爬他的code總算找到我所需要的指令 listCollections,以下直接上code
$manager = new MongoDB\Driver\Manager("mongodb://帳號:密碼@主機ip:27017/資料庫");
cmd = new MongoDB\Driver\Command([
'listCollections' => 1,
'cursor' => new stdClass,
]);
$cursor = $manager->executeCommand('資料庫', $cmd);
$collections_ar=array();
foreach ($cursor as $document) {
array_push($collections_ar,$document->name);//集合名稱存成陣列
}
rsort($collections_ar);//我的需求是 大到小排序
print_r($collections_ar);
顯示結果
Array ( [0] => log_2020_03_31 [1] => log_2020_03_30 [2] => log_2020_03_27 [3] => log_2020_03_26 [4] => log_2020_03_25 [5] => log_2020_03_24 [6] => log_2020_03_23 [7] => log_2020_03_22 [8] => log_2020_03_21 [9] => log_2020_03_20 [10] => log_2020_03_19 [11] => log_2020_03_18 [12] => log_2020_03_17 [13] => log_2020_03_16 [14] => log_2020_03_15 [15] => log_2020_03_14 [16] => log_2020_03_13 [17] => log_2020_03_12 [18] => log_2020_03_11 [19] => log_2020_03_10 [20] => log_2020_03_09 [21] => log_2020_03_08 [22] => log_2020_03_07 [23] => log_2020_03_06 [24] => log_2020_03_05 [25] => log_2020_03_04 [26] => log_2020_03_03 [27] => log_2020_03_02 [28] => log_2020_03_01 )
參考連結:https://github.com/mongodb/mongo-php-library/blob/master/src/Operation/ListCollections.php