To list collections in a MongoDB database, you can use the following methods depending on the context you’re working in (MongoDB shell, a GUI tool, or a programming language).
1. Using MongoDB Shell
In the MongoDB shell, you can use the following command to list all collections in the currently selected database:
show collections
Alternatively, you can also use:
db.getCollectionNames()
2. Using MongoDB Compass
- Connect to your MongoDB instance.
- Select the database you are interested in.
- You will see a list of collections in the left sidebar.
3. Using a Programming Language
Node.js Example
If you’re using Node.js with the MongoDB driver:
const { MongoClient } = require('mongodb');
async function listCollections() {
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const database = client.db('mydatabase');
const collections = await database.listCollections().toArray();
console.log(collections.map(col => col.name));
await client.close();
}
listCollections().catch(console.error);
Python Example
If you’re using Python with PyMongo:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017')
db = client.mydatabase
collections = db.list_collection_names()
print(collections)
Summary
- Use
show collectionsordb.getCollectionNames()in the MongoDB shell. - View collections in MongoDB Compass through the UI.
- Use
listCollections()in your application code to retrieve collections programmatically.
