Listing Collections in MongoDB

When working with MongoDB, you may need to view all collections in your current database. Here are several methods to accomplish this using the MongoDB shell.

Method 1: Using show collections

The simplest way to list all collections is by using the show collections command. First, ensure you have selected the desired database using the use command:

use <database_name>
show collections

This command will return a list of all non-system collections in the selected database.

Method 2: Using db.getCollectionNames()

Another method is to use the db.getCollectionNames() function, which returns an array of collection names:

db.getCollectionNames()

This will provide a straightforward list of all collections in the current database.

Method 3: Using db.runCommand() with listCollections

For more detailed information, you can use the listCollections command through db.runCommand(). This command returns a document with collection options:

db.runCommand({ listCollections: 1 })

You can also specify options to filter the results, such as:

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

Method 4: Using db.getCollectionInfos()

If you need comprehensive details about each collection, use the db.getCollectionInfos() method:

db.getCollectionInfos()

This will return an array of documents containing metadata about each collection, including options and statistics.

Conclusion

These commands provide various ways to list collections in MongoDB, catering to different needs for simplicity or detail. Choose the method that best fits your requirements.