How to show collections in MongoDB
List every collection in a MongoDB database with show collections, db.getCollectionNames() or listCollections, from mongosh, Node.js or Python.
Quick Answer
Switch to the database, then run show collections:
use shop
show collections
For an array you can use in a script, call db.getCollectionNames().
List collections in mongosh
show collections works on whatever database you are using right now. If it prints nothing, check you are in the right one with db. A new connection starts in test, which is usually empty.
| Command | Returns | Use it when |
|---|---|---|
show collections | Sorted names, with views and time-series marked | You are looking at the shell |
db.getCollectionNames() | An array of strings | You want to loop over names in a script |
db.getCollectionInfos() | An array of documents | You also need the type, options or validator |
// every collection with a rough document count
db.getCollectionNames().forEach(name => {
print(name, db.getCollection(name).estimatedDocumentCount())
})
// another database, without switching
db.getSiblingDB('analytics').getCollectionNames()
Filter: only collections, only views, or by name
The listCollections command behind these helpers accepts a filter, so you can ask for one kind:
db.getCollectionInfos({ type: 'collection' }).map(c => c.name) // no views
db.getCollectionInfos({ type: 'view' }).map(c => c.name) // views only
db.getCollectionNames().filter(n => !n.startsWith('system.')) // hide internal ones
Names that start with system., such as system.views, system.profile or system.buckets.metrics, are internal collections MongoDB manages. Read them if you need to, but don't write to them directly.
From Node.js
import { MongoClient } from 'mongodb'
const client = new MongoClient(process.env.MONGODB_URI)
const names = (await client.db('shop')
.listCollections({}, { nameOnly: true, authorizedCollections: true })
.toArray()).map(c => c.name)
console.log(names) // [ 'orders', 'customers', 'products' ]
await client.close()
nameOnly makes the reply smaller and faster. authorizedCollections lets users who can only read some collections list those, instead of getting an error (see below).
From Python (PyMongo)
from pymongo import MongoClient
db = MongoClient("mongodb://localhost:27017")["shop"]
print(db.list_collection_names()) # ['orders', 'customers']
print(db.list_collection_names(filter={"type": "collection"})) # skip views
print(db.list_collection_names(authorizedCollections=True)) # for limited users
Why the list is empty or fails
- Wrong database. Run
dbto check, thenshow dbsto see what exists. - The database was never written to. MongoDB creates a database and its first collection on the first insert.
use newdbalone creates nothing. - "not authorized on shop to execute command { listCollections: ...". Your user can read some collections but doesn't have the
listCollectionsprivilege on the database. Usedb.runCommand({ listCollections: 1, nameOnly: true, authorizedCollections: true })to list the collections you can access.
What we found testing this
show collectionsfails for limited users, despite what the docs say. The MongoDB docs say it sendsauthorizedCollections: true. In mongosh 2.9.2 it sentauthorizedCollections: false, so a user withfindon a single collection gotMongoServerError[Unauthorized]: not authorized on <db> to execute command { listCollections: 1, ... authorizedCollections: false ... }.db.getCollectionNames(), the Node driver'slistCollections()and PyMongo'slist_collection_names()failed the same way. Only an explicitauthorizedCollections: truereturned the one allowed collection.- Only
show collectionssorts. It printed names case-insensitively (alpha,alpha_view [view],Beta,metrics [time-series],zeta) withsystem.*collections listed last.db.getCollectionNames()andlistCollectionsreturned the server's order, unsorted, withsystem.profilefirst. Sort in your script if order matters. - System collections do appear. With the profiler on, a view and a time-series collection in the database,
show collectionsalso listedsystem.profile,system.viewsandsystem.buckets.metrics. That last one is the hidden storage behind the time-series collectionmetrics. nameOnlyis about 3ร faster on big databases. With 2,000 collections (half with validators), the fulllistCollectionstook 15.9 ms and returned 369 KB. WithnameOnly: trueit took 5.5 ms and 94 KB.db.getCollectionNames()took 11.6 ms. Averages of 20 runs, MongoDB 7.0 in local Docker.
Frequently Asked Questions
What is the difference between show collections and db.getCollectionNames()?
They list the same collections. show collections prints them sorted and marks views and time-series collections; db.getCollectionNames() returns an unsorted array you can use in a script.
Does show collections include views?
Yes, marked [view]. Use db.getCollectionInfos({ type: "collection" }) if you want real collections only.
Why does show collections say not authorized when I can read the collections?
Your user lacks the database-wide listCollections privilege. Run db.runCommand({ listCollections: 1, nameOnly: true, authorizedCollections: true }) to list only the collections you have access to.
How do I count the documents in every collection?
Loop over db.getCollectionNames() and call estimatedDocumentCount() on each. It reads collection metadata, so it is fast even on large collections.