MongoDB mongosh Create Collection

MongoDB mongosh Create Collection
In MongoDB mongosh Create Collection are created automatically when you insert data.
You can also create them explicitly using a command.
There is no fixed schema like SQL tables.
1️⃣ Start mongosh
Open Terminal / Command Prompt and run:
You’ll see:
2️⃣ Switch to a Database (Required)
Output:
If the database doesn’t exist, MongoDB will create it later when data is inserted.
3️⃣ Create Collection Automatically (Most Common)
MongoDB creates a collection when you insert a document.
This automatically creates:
myDatabase(if not exists)userscollection
4️⃣ Verify Collections
Output:
5️⃣ Create Collection Explicitly (Empty Collection)
If you want to create a collection without inserting data:
Output:
Now check:
6️⃣ Create Multiple Collections
MongoDB automatically creates:
productsorders
7️⃣ Create Collection with Options (Interview Tip)
Example: capped collection (fixed size)
Used in logging and streaming scenarios.
8️⃣ Delete a Collection (Extra)
Deletes the
userscollection permanently.
Key Points (Very Important for Exams & Interviews)
✔ Collections are like tables (but schema-less)
✔ Automatically created on first insert
✔ createCollection() creates empty collection
✔ No need to define structure in advance
✔ One database can have many collections
Common Interview Questions
Q1. How is a collection created in MongoDB?
👉 Automatically when data is inserted
Q2. Can we create an empty collection?
👉 ✅ Yes, using db.createCollection()
Q3. Does MongoDB require schema before creating collection?
👉 ❌ No
Q4. Difference between table and collection?
👉 Table = fixed schema
👉 Collection = flexible schema
Summary
🎉 That’s everything you need to know about creating collections in MongoDB using mongosh.
