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:

javascript
show collections

Alternatively, you can also use:

javascript
db.getCollectionNames()

2. Using MongoDB Compass

  1. Connect to your MongoDB instance.
  2. Select the database you are interested in.
  3. 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:

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

python
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017')
db = client.mydatabase
collections = db.list_collection_names()

print(collections)

Summary

  • Use show collections or db.getCollectionNames() in the MongoDB shell.
  • View collections in MongoDB Compass through the UI.
  • Use listCollections() in your application code to retrieve collections programmatically.

Sign In

Sign Up