listCollections(列出集合)
最后更新:2026-10-09
listCollections(列出集合)
listCollections返回数据库中的集合及选项(validator、collation、TTL等)。mongosh中用db.getCollectionNames()(仅名字)或db.getCollectionInfos()(含详情)。filter参数可按name、type过滤(如只看视图)。结果以游标形式返回,需遍历取全。
| 分类 | 管理命令 |
|---|---|
| MongoDB 版本 | 1.0+ |
| 示例语言 | mongosh (Shell) |
📝 语法
db.runCommand({ listCollections: 1, filter: { name: /^orders/ } })
db.getCollectionInfos({ name: /^orders/ })
⚙️ 参数
| filter | 按name、type、options等字段过滤 |
|---|---|
| nameOnly | true时只返回集合名 |
返回值:返回游标,firstBatch包含各集合的name、type与options
▶ 示例
请在本地安装的 mongosh 中执行以下命令(需已启动 mongod):
// listCollections:列出所有集合
use shop
db.getCollectionInfos().forEach((c) => print(c.name))
运行结果:
orders
products
users
📌 注意事项
- 返回游标,遍历firstBatch取全部
- filter支持按name、type、options过滤
- 默认包含system.*集合,可按name过滤排除
🏷️ 相关标签
💡 相关案例
更多实战案例即将上线,敬请期待。
📚 相关教程
❓ 常见问题
QlistCollections和getCollectionNames有什么区别?
AgetCollectionNames只返回名字列表,listCollections含集合选项详情。
Q能过滤视图吗?
A用filter: { type: 'view' }只列视图。
Q返回的是什么?
A游标,遍历firstBatch拿集合元数据。