How to Show All Collections in MongoDB Quickly
To show all collections in MongoDB, use the
show collections command in the MongoDB shell or call db.getCollectionNames() in your code. These commands list all collection names in the current database.Syntax
There are two common ways to list collections in MongoDB:
show collections: A shell command that lists all collections in the current database.db.getCollectionNames(): A JavaScript method that returns an array of collection names.
mongodb
show collections // or in JavaScript const collections = db.getCollectionNames(); printjson(collections);
Example
This example shows how to list all collections in the test database using the MongoDB shell.
mongodb
use test show collections
Output
users
products
orders
Common Pitfalls
Some common mistakes when listing collections include:
- Running
show collectionswithout selecting a database first, which will list collections from the default database. - Using
db.getCollectionNames()without a proper database context. - Expecting collection details instead of just names; these commands only list names.
mongodb
/* Wrong: No database selected */ show collections /* Right: Select database first */ use myDatabase show collections
Quick Reference
| Command/Method | Description |
|---|---|
| show collections | Lists all collections in the current database in the shell |
| db.getCollectionNames() | Returns an array of collection names in JavaScript |
| use | Switches to the specified database |
Key Takeaways
Use
show collections in the MongoDB shell to list all collections in the current database.Use
db.getCollectionNames() in scripts to get an array of collection names.Always select the correct database with
use <database> before listing collections.These commands only show collection names, not their contents or details.