在MongoDB shell中,如何列出当前使用的数据库的所有集合?


当前回答

首先,您需要使用数据库来显示其中的所有集合/表。

>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

其他回答

>显示表格

它给出了与卡梅伦的答案相同的结果。

如何列出当前使用的数据库的所有集合?

三种方法

显示表显示表格db.getCollectionNames()


要列出所有数据库:

show dbs

要输入或使用给定数据库:

use databasename

要列出所有集合:

show collections

输出:

集合1集合2系统索引

(or)

show tables

输出:

集合1集合2系统索引

(or)

db.getCollectionNames()

输出:

[“collection1”,“collection2”,“system.indexs”]


输入或使用给定集合

use collectionname

列出mongo shell中的所有集合:

db.getCollectionNames()显示表显示表格注意:集合将显示您所在的当前数据库目前

我认为最大的困惑之一是使用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'))})"

首先,您需要使用数据库来显示其中的所有集合/表。

>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