HOWTO · MongoDB
如何在 MongoDB 中列出集合
學習如何在 mongosh 中使用 show collections、getCollectionNames、listCollections 和 getCollectionInfos 列出 MongoDB 集合。
本頁內容
MongoDB 會將文件儲存在集合中。當你需要查看資料庫中有哪些集合時,可以使用下列 mongosh 命令或輔助方法。最簡短的答案是 show collections;其他選項則會返回 JavaScript 陣列或可供篩選的集合中繼資料。
選取要檢查的資料庫
列出集合的命令會作用於目前的資料庫。執行任何範例前,先選取資料庫:
use catalog
將 catalog 換成你的資料庫名稱。資料庫名稱會區分大小寫。如果你不確定伺服器上有哪些資料庫,可以先執行 show dbs,再切換到要檢查的資料庫。
使用 show collections 快速列出集合
當你只需要在互動式 Shell 中取得易讀的清單時,執行以下 mongosh 命令:
show collections
輸出會依目前資料庫中的集合和檢視而不同。mongosh 可以在輸出中標示 view 和 time-series collection。具有必要權限時,show collections 會列出資料庫中的非系統集合;權限受限時,只會列出使用者能存取的集合。
像 system.views 這類名稱是 MongoDB 為支援檢視而產生的名稱,不是應用程式集合。
這個命令適合在 Shell 提示字元中快速確認。若指令碼需要陣列、集合選項,或需要篩選結果,就應該使用其他方法。
使用 db.getCollectionNames() 返回集合名稱
db.getCollectionNames() 會返回目前資料庫中集合和檢視的名稱陣列:
db.getCollectionNames()
例如,包含兩個集合和一個檢視的資料庫可能返回以下陣列:
[ "activeProducts", "clients", "products", "system.views" ]
返回的順序不應視為可靠的排序。如果順序很重要,請在 JavaScript 程式碼中排序:
db.getCollectionNames().sort()
當你要在迴圈或小型 Shell 指令碼中使用名稱時,這個方法很方便。但它不會返回集合選項,也不會告訴你每個名稱代表一般集合、view 或 time-series collection。
使用 listCollections 返回原始命令結果
listCollections 資料庫命令會返回包含集合和檢視資訊的游標。只需要每個名稱和類型時,使用 nameOnly: true:
db.runCommand({
listCollections: 1,
nameOnly: true,
authorizedCollections: true
})
cursor.firstBatch 中的文件會以 name 和 type 識別每個資料儲存區,類型可能是 collection、view 或 timeseries。需要集合選項、唯讀狀態、UUID 或 _id 索引資訊時,移除 nameOnly: true。這個命令返回未排序的清單;若需要固定順序,請在用戶端排序結果。
authorizedCollections: true 必須和 nameOnly: true 一起使用才會產生這裡所說的效果。即使使用者沒有資料庫層級的 listCollections 權限,也可以查看其擁有權限的集合名稱和類型。沒有必要存取權限時,完整的中繼資料形式可能會返回授權錯誤。
使用 db.getCollectionInfos() 檢查或篩選中繼資料
db.getCollectionInfos(filter, options) 是 mongosh 中用於檢查集合中繼資料的方法。若只要名稱和類型,請在 options 文件中傳入 nameOnly:
db.getCollectionInfos({}, { nameOnly: true })
包含一個檢視和兩個集合的資料庫可能產生以下輸出:
[{"name":"activeProducts","type":"view"},{"name":"clients","type":"collection"},{"name":"products","type":"collection"},{"name":"system.views","type":"collection"}]
要檢查單一集合,可以依名稱篩選:
db.getCollectionInfos(
{ name: "clients" },
{ nameOnly: true }
)
[{"name":"clients","type":"collection"}]
如果篩選條件沒有符合的集合,方法會返回空陣列:
db.getCollectionInfos(
{ name: "missing" },
{ nameOnly: true }
)
[]
需要 options、info.readOnly、info.uuid 或 idIndex 等中繼資料時,省略 nameOnly。UUID 會針對特定集合產生,因此不要將範例中的 UUID 複製到文件或測試預期中。你也可以依中繼資料返回的欄位篩選,例如 { "info.readOnly": true }。
選擇適合的集合列表方法
| 需求 | 使用方法 |
|---|---|
在 mongosh 中快速取得易讀清單 |
show collections |
| 取得名稱的 JavaScript 陣列 | db.getCollectionNames() |
| 取得原始資料庫命令和游標 | db.runCommand({ listCollections: 1, ... }) |
| 取得集合/檢視中繼資料或進行篩選 | db.getCollectionInfos(filter, options) |
以上命令適用於目前的 mongosh Shell。較舊的教學可能使用舊版 mongo Shell;目前的 MongoDB 安裝請使用 mongosh。可用的名稱和中繼資料仍取決於選取的資料庫及使用者權限。在複本集成員上執行時,listCollections 操作要求成員處於 PRIMARY 或 SECONDARY 狀態。
如需完整欄位清單和存取規則,請參閱 MongoDB 對 listCollections、db.getCollectionInfos() 和 db.getCollectionNames() 的文件。