MongoDB mongosh Create Collection

MongoDB Tutorial

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:

mongosh

You’ll see:

test>

2️⃣ Switch to a Database (Required)

use myDatabase

Output:

switched to db myDatabase

 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.

db.users.insertOne({
name: "Amit",
age: 25,
city: "Delhi"
})

 This automatically creates:

  • myDatabase (if not exists)

  • users collection


4️⃣ Verify Collections

show collections

Output:

users

5️⃣ Create Collection Explicitly (Empty Collection)

If you want to create a collection without inserting data:

db.createCollection("employees")

Output:

{ ok: 1 }

Now check:

show collections
users
employees

6️⃣ Create Multiple Collections

db.products.insertOne({ name: "Laptop", price: 50000 })
db.orders.insertOne({ orderId: 101, status: "Placed" })

MongoDB automatically creates:

  • products

  • orders


7️⃣ Create Collection with Options (Interview Tip)

Example: capped collection (fixed size)

db.createCollection("logs", {
capped: true,
size: 1024,
max: 100
})

 Used in logging and streaming scenarios.


8️⃣ Delete a Collection (Extra)

db.users.drop()

 Deletes the users collection 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

use myDatabase
db.collection.insertOne({ key: "value" })
show collections
db.createCollection("collectionName")

🎉 That’s everything you need to know about creating collections in MongoDB using mongosh.

You may also like...