How to list all collections in the mongo shell?

2019-01-12 13:24发布

In the MongoDB shell, how do I list all collections for the current database that I'm using?

21条回答
成全新的幸福
2楼-- · 2019-01-12 13:57

For MongoDB 3.0 deployments using the WiredTiger storage engine, if you run db.getCollectionNames() from a version of the mongo shell before 3.0 or a version of the driver prior to 3.0 compatible version, db.getCollectionNames() will return no data, even if there are existing collections.

For further details, please refer to this

查看更多
Anthone
3楼-- · 2019-01-12 13:59

You can do...

JS (shell):

db.getCollectionNames()

node.js:

db.listCollections()

non-JS (shell only):

show collections

The reason I call that non-JS is because:

$ mongo prodmongo/app --eval "show collections"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
2016-10-26T19:34:34.886-0400 E QUERY    [thread1] SyntaxError: missing ; before statement @(shell eval):1:5

$ mongo prodmongo/app --eval "db.getCollectionNames()"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
[
    "Profiles",
    "Unit_Info"
]

If you really want that sweet, sweet show collections output, you can:

$ mongo prodmongo/app --eval "db.getCollectionNames().join('\n')"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
Profiles
Unit_Info
查看更多
唯我独甜
4楼-- · 2019-01-12 13:59

On >=2.x, you can do

db.listCollections()

On 1.x you can do

db.getCollectionNames()
查看更多
登录 后发表回答