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

If you want to show all collections from mongodb shell (command line), use shell helper

show collections

that show all collections for current database. If you want to get all collection list from your application then you can use mongodb database method

db.getCollectionNames()

For more info mongodb shell helper you can seee http://docs.mongodb.org/manual/reference/mongo-shell/

查看更多
神经病院院长
3楼-- · 2019-01-12 13:51

show collections

this command usually works on mongo shell once you have switched to the database.

查看更多
男人必须洒脱
4楼-- · 2019-01-12 13:52

I think one of the biggest confusions is the difference between what you can do with mongo (or an interactive/hybrid shell) vs. mongo --eval (or a pure javascript shell). I keep these helpful documents handy:

Here is an example of scripting what you might otherwise do with show commands:

# 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')
            )
        }
    )
"

Note: That works really well as a oneliner. (But looks terrible on StackOverflow.)

mongo --eval "db.getMongo().getDBNames().forEach(function(v, i){print(v+'\n\t'+db.getSiblingDB(v).getCollectionNames().join('\n\t'))})"
查看更多
时光不老,我们不散
5楼-- · 2019-01-12 13:54
 1. show collections; //Display all collection
 2. show tables     //Display all collection
 3. db.getCollectionNames();   // Retuen array of collection Example :[ "orders", "system.profile" ]

Details information of every collection

db.runCommand( { listCollections: 1.0, authorizedCollections: true, nameOnly: true } )
  • For users with the required access (privileges that grant listCollections action on the database), the method lists the names of all collections for the database.
  • For users without the required access, the method lists only the collections for which the users has privileges. For example, if a user has find on a specific collection in a database, the method would return just that collection.
查看更多
We Are One
6楼-- · 2019-01-12 13:55

List all collections from the mongo shell :

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

Note : Collections will show from current database where you are in currently

查看更多
萌系小妹纸
7楼-- · 2019-01-12 13:57

Try:

help // To show all help methods
show dbs  // To show all dbs
use dbname  // To select your db
show collections // To show all collections in selected db
查看更多
登录 后发表回答