Chapter 5: MongoDB mongosh Create Collection
What is MongoDB mongosh Create Collection?
Just like databases, MongoDB is very relaxed about collections too (collections = tables in SQL world).
Big truth first (write in big letters!):
MongoDB does NOT require you to create a collection before using it. Most of the time, you never explicitly create a collection — it magically appears the first time you insert a document into it.
But sometimes you want to create it explicitly — especially when you need special settings like:
- Capped collections (fixed size, auto-deletes old data like a circular log)
- Time-series collections (for IoT/sensor data, optimized storage)
- Schema validation (force certain fields/types — like “light schema”)
- TTL indexes (auto-expire documents after time)
- Specific storage options, collation, etc.
The command for explicit creation in mongosh is: db.createCollection(“collectionName”, { options })
Two Ways to “Create” a Collection in mongosh
| Way | How it happens | When to use | Command Example |
|---|---|---|---|
| Implicit (Automatic – 95% of cases) | Happens when you first insertOne(), insertMany(), etc. | Everyday apps, quick prototyping | db.students.insertOne({ name: “Rahul” }) → creates students if missing |
| Explicit (Using createCollection) | You run db.createCollection() first | Need special options (capped, time-series, validation, etc.) | db.createCollection(“logs”, { capped: true, size: 1000000 }) |
Hands-on – Let’s Do Both Ways Right Now
Assume you’re already connected in mongosh and switched to a database:
|
0 1 2 3 4 5 6 |
use college2026 |
Way 1: Implicit Creation (Super Simple – Do This Most of the Time)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// This creates the collection "students" automatically if it doesn't exist db.students.insertOne({ name: "Priya Patel", rollNo: "2026HYD001", age: 18, city: "Hyderabad", branch: "CSE", hobbies: ["coding", "cricket"] }) db.students.find().pretty() // See your document |
Now check:
|
0 1 2 3 4 5 6 |
show collections |
You should see students listed!
→ No createCollection needed. MongoDB handles it for you.
Way 2: Explicit Creation with db.createCollection() (When You Need Control)
Basic empty collection (rarely needed, but good to know):
|
0 1 2 3 4 5 6 |
db.createCollection("teachers") |
Now show collections → you’ll see teachers even though it’s empty.
But the real power is in options:
Example 1: Capped Collection (Fixed size, oldest data auto-deletes – great for logs)
|
0 1 2 3 4 5 6 7 8 9 10 |
db.createCollection("serverLogs", { capped: true, // Must be true for capped size: 5242880, // ~5 MB max size (in bytes) max: 5000 // Optional: max 5000 documents }) |
After creation:
|
0 1 2 3 4 5 6 |
db.serverLogs.stats() // See "capped: true", "maxSize", etc. |
Insert some logs:
|
0 1 2 3 4 5 6 7 8 9 |
db.serverLogs.insertMany([ { timestamp: new Date(), message: "User login success" }, { timestamp: new Date(), message: "API rate limit hit" } ]) |
When it fills up → oldest documents disappear automatically. Like a rolling window.
Example 2: Time-Series Collection (Very popular in 2026 for metrics, IoT, stock prices)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
db.createCollection("temperatureReadings", { timeseries: { timeField: "timestamp", // Required: field with dates metaField: "sensorId", // Optional: group by this (e.g., device ID) granularity: "minutes" // seconds / minutes / hours }, expireAfterSeconds: 7776000 // Optional: auto-delete after ~90 days (in seconds) }) |
Insert example:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
db.temperatureReadings.insertOne({ timestamp: new Date(), sensorId: "TEMP-SENSOR-001-HYD", value: 28.5, location: "Server Room" }) |
→ Optimized storage, faster range queries on time.
Example 3: With Schema Validation (Enforce some rules – like “light contract”)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
db.createCollection("employees", { validator: { $jsonSchema: { bsonType: "object", required: ["name", "empId", "salary"], properties: { name: { bsonType: "string" }, empId: { bsonType: "string" }, salary: { bsonType: "number", minimum: 20000 }, department: { enum: ["IT", "HR", "Finance", null] } } } }, validationLevel: "moderate", // strict / moderate validationAction: "error" // error / warn }) |
Now if you try to insert invalid data:
|
0 1 2 3 4 5 6 |
db.employees.insertOne({ name: "Amit", salary: 15000 }) // Fails! salary too low |
→ Great for preventing bad data in production.
Quick Summary Table
| Feature You Want | Use Implicit? | Use db.createCollection? | Example Command Snippet |
|---|---|---|---|
| Normal flexible collection | Yes | No (optional) | db.items.insertOne({…}) |
| Capped / fixed-size log | No | Yes | { capped: true, size: 1e6 } |
| Time-series (sensor/metric data) | No | Yes | { timeseries: { timeField: “ts” } } |
| Enforce schema rules | No | Yes | { validator: { $jsonSchema: … } } |
| TTL auto-expire documents | No (index) | Sometimes | Create TTL index after |
| Just want empty collection first | No | Yes | db.createCollection(“temp”) |
How to Check / List Collections
|
0 1 2 3 4 5 6 7 8 |
show collections // Simple list db.getCollectionNames() // Array output db.collection.stats("students") // Detailed info about one |
Mini Exercise – Try Now!
- use myValentineDb
- Create a capped loveNotes collection:
|
0 1 2 3 4 5 6 |
db.createCollection("loveNotes", { capped: true, size: 100000 }) |
- Insert few notes:
|
0 1 2 3 4 5 6 7 8 9 |
db.loveNotes.insertMany([ { from: "Rahul", to: "Priya", message: "Happy Valentine's ❤️", time: new Date() }, { from: "Amit", to: "Sneha", message: "You are my MongoDB query!", time: new Date() } ]) |
- show collections → see it!
- Insert 100+ small docs → watch oldest disappear when size limit hits.
Understood everything? This is one of those “MongoDB is flexible but gives power when needed” moments.
Next class options:
- How to drop a collection safely?
- Rename collection?
- Create indexes for fast queries?
- Schema validation deep dive?
- Or start a small project like “Valentine Wishlist App” with collections?
Tell me what you want next — class is open! 🚀😄
Any doubt in today’s topic? Ask freely!
