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:41

I use listCollections (supports mongo 3.0 and up) for this purpose.

example:

db.runCommand({ listCollections: 1, filter: {}, nameOnly: true });

To fetch more info like index of the collection:

db.runCommand({ listCollections: 1, filter: {}, nameOnly: false });

To print just the collection names:

db.runCommand({ listCollections: 1, filter: {}, nameOnly: true }).cursor.firstBatch.forEach(v => {print(v.name)})

I feel this provide more flexibility.

read more: https://docs.mongodb.com/manual/reference/command/listCollections/

查看更多
我命由我不由天
3楼-- · 2019-01-12 13:43

how do I list all collections for the current database that I'm using?

3 Methods

  • show collections
  • show tables
  • db.getCollectionNames()

To list all databases:

show dbs

To enter or use given database:

use databasename

To list all collections:

show collections

Output:

collection1  
collection2  
system.indexes

(or)

show tables

Output:

collection1  
collection2  
system.indexes

(or)

db.getCollectionNames()

Output:

[ "collection1", "collection2", "system.indexes" ]

To enter or use given collection

use collectionname
查看更多
聊天终结者
4楼-- · 2019-01-12 13:44
> show collections

will list all the collections in the currently selected DB, as stated in the command line help (help).

查看更多
对你真心纯属浪费
5楼-- · 2019-01-12 13:47

> show tables

It gives the same result as Cameron's answer.

查看更多
Bombasti
6楼-- · 2019-01-12 13:49

Apart from the options suggested by other people:

show collections  //output every collection
show tables
db.getCollectionNames() //shows all collections as a list

There is also another way which can be really handy if you want to know how each of the collections was created (for example it is a capped collection with a particular size)

db.system.namespaces.find()
查看更多
手持菜刀,她持情操
7楼-- · 2019-01-12 13:49
> show dbs        
anuradhfirst  0.000GB
local         0.000GB
> use anuradhfirst
switched to db anuradhfirst
> show collections
record
  • connect with mongo database using mongo, this will start the connection.
  • then run show dbs command, this will show you all exiting/available database.
  • then select the database you want.in above it is anuradhfirst, then run use anuradhfirst.this will switch to the database you want.
  • then run show collections command, this will show all the collections inside your selected database.
查看更多
登录 后发表回答