在MongoDB shell中,如何列出当前使用的数据库的所有集合?
当前回答
为此,我使用listCollections(支持MongoDB 3.0及更高版本)。
例子:
db.runCommand({ listCollections: 1, filter: {}, nameOnly: true });
要获取更多信息,如集合的索引:
db.runCommand({ listCollections: 1, filter: {}, nameOnly: false });
要仅打印集合名称:
db.runCommand({ listCollections: 1, filter: {}, nameOnly: true }).cursor.firstBatch.forEach(v => {print(v.name)})
我觉得这提供了更多的灵活性。
阅读更多:listCollections
其他回答
如果要显示MongoDB shell(命令行)中的所有集合,请使用shell助手,
show collections
显示当前数据库的所有集合。如果您想从应用程序中获取所有集合列表,那么可以使用MongoDB数据库方法
db.getCollectionNames()
有关MongoDB shell助手的更多信息,请参阅mongoShell快速参考。
我认为最大的困惑之一是使用mongo(或交互式/混合shell)与mongo-eval(或纯JavaScript shell)之间的区别。我将这些有用的文档放在手边:
交互式蒙哥和脚本蒙哥的区别Mongo Shell命令帮助程序
下面是一个脚本示例,您可以使用show命令执行以下操作:
# List all databases and the collections in them
mongo --eval "
db.getMongo().getDBNames().forEach(
function(v, i){
print(
v + '\n\t' +
db.getSiblingDB(v).getCollectionNames().join('\n\t')
)
}
)
"
注意:这是一个很好的单行程序。(但在堆栈溢出上看起来很糟糕。)
mongo --eval "db.getMongo().getDBNames().forEach(function(v, i){print(v+'\n\t'+db.getSiblingDB(v).getCollectionNames().join('\n\t'))})"
对于使用WiredTiger存储引擎的MongoDB 3.0部署,如果从mongo shell的一个版本运行db.getCollectionNames()3.0之前的版本或3.0兼容版本之前的驱动程序版本,db.getCollectionNames()将不返回任何数据,即使存在现有集合。
有关详细信息,请参阅。
mongoshell上的以下命令是常见的。
show databases
show collections
而且
show dbs
use mydb
db.getCollectionNames()
有时,查看所有集合以及作为整体命名空间一部分的集合上的索引很有用:
以下是您的操作方法:
db.getCollectionNames().forEach(function(collection) {
indexes = db[collection].getIndexes();
print("Indexes for " + collection + ":");
printjson(indexes);
});
在这三个命令和这段代码之间,您应该很熟悉!
首先,您需要使用数据库来显示其中的所有集合/表。
>show dbs
users 0.56787GB
test (empty)
>db.test.help() // this will give you all the function which can be used with this db
>use users
>show tables //will show all the collection in the db
推荐文章
- 如何排序mongodb与pymongo
- 如何在mongodb上导入。bson文件格式
- JSON文件的蒙古导入
- 如何删除mongodb中的数组元素?
- 修改MongoDB数据存储目录
- 在MongoDB中查找重复的记录
- 为什么MongoDB Java驱动在条件中使用随机数生成器?
- 在猫鼬,我如何排序的日期?(node . js)
- 将映像存储在MongoDB数据库中
- 重复Mongo ObjectId的可能性在两个不同的集合中生成?
- Redis比mongoDB快多少?
- 无法连接到服务器127.0.0.1:27017
- 如何创建数据库的MongoDB转储?
- 如何将MongoDB作为Windows服务运行?
- 如何监听MongoDB集合的变化?