MongoDB Collections: Show, Create, Rename & Drop Collection
Learn how to list, create, rename, and delete collections in MongoDB, including createCollection() and the two ways collections get created automatically.
MongoDB Collections
Show Collections
show collections (or show tables) lists every collection in the currently selected database.
use rahultechnology
show collections
// emp
show tables
// emp
Create a Collection
MongoDB stores documents in collections — the equivalent of tables in a relational database. There are two ways to create one:
1. Explicitly, with createCollection():
db.createCollection("emp1")
// { ok: 1 }
2. Implicitly, by inserting into it:
db.emp2.insertOne({ name: "rahul" })
// A collection named "emp2" is created automatically if it doesn't exist.
show collections
// emp
// emp1
// emp2
Rename a Collection
Use db.collection.renameCollection() to fix a typo'd or outdated collection name without losing its data.
db.emp1.renameCollection("emp11")
// { ok: 1 }
show collections
// emp
// emp11
// emp2
Advertisement728 x 90
Delete / Drop a Collection
db.collection.drop() permanently deletes a collection. It returns true on success — once dropped, the data cannot be recovered.
db.emp.drop()
// true
db.emp1.drop()
// false (already renamed, so it no longer exists)
show collections
Common Errors & Troubleshooting
MongoServerError: Collection already exists— thrown bycreateCollection()if you try to explicitly create a collection that already exists. Checkshow collectionsfirst, or just skipcreateCollection()and let an insert create it implicitly.- A dropped collection's data is unrecoverable —
drop()has no undo. If you're not certain, rename it first withrenameCollection()(or take a backup withmongodump) instead of dropping outright. - Renaming to a name that already exists —
renameCollection()fails by default if the target name is taken; passrenameCollection("newName", true)to explicitly allow overwriting it (drops the old target collection first).
Key Takeaways
- A collection can be created explicitly (
createCollection()) or automatically on first insert. renameCollection()renames in place — no data is lost.drop()is permanent — there is no "undo" or recycle bin.
Advertisement320 x 100