MongoDB Collections
What Is Collections?
A collection is a group of documents inside a database, similar to a table in a relational database but without a fixed schema. Collections are created implicitly the first time you insert into them, or explicitly with db.createCollection() when you need options such as validation, a collation, or a capped size.
Why It Matters
| Reason | Benefit |
|---|---|
| Organizes your data | Each entity type (users, orders, products) gets its own collection. |
| Indexes live here | Indexes are defined per collection, so collections are your unit of performance tuning. |
| Optional validation | A validator lets you enforce required fields and types without giving up flexibility elsewhere. |
| Simple lifecycle | Create implicitly, drop with one call, and rename when your model changes. |
How To Use It
- Switch to a database with use school.
- Run show collections to see what already exists (probably nothing).
- Create one implicitly with db.students.insertOne({ name: "Ravi" }).
- Create another explicitly with db.createCollection("courses").
- List them again with show collections.
- Rename a collection with db.courses.renameCollection("classes") if needed.
- Remove one with db.classes.drop() and confirm the result is true.
mongosh Examples
use school
// Implicit creation on first insert
db.students.insertOne({ name: "Ravi", grade: 10 })
// Explicit creation with a validator
db.createCollection("courses", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["title"],
properties: { title: { bsonType: "string" } }
}
}
})
show collections
db.getCollectionNames()
// Capped collection: 1 MB, oldest documents are overwritten
db.createCollection("recentLogs", { capped: true, size: 1048576 })
db.courses.renameCollection("classes")
db.classes.drop() Edge Cases & Pitfalls
drop() is permanent
Dropping a collection removes its documents and indexes immediately. Double-check the name first.
Capped collections have limits
You cannot delete individual documents from a capped collection, and sharding is not supported for them. Use them only for fixed-size, insertion-order workloads.
Validation applies to new writes
Adding a validator does not rewrite existing documents; it governs inserts and updates after that.
Names to avoid
Collection names cannot be empty, contain the null character, or start with system. which is reserved.
Cheat Sheet
| Topic | Detail |
|---|---|
| show collections | List collections in the current database |
| db.getCollectionNames() | Return collection names as an array |
| db.createCollection(name) | Create a collection explicitly, optionally with options |
| db.myColl.insertOne({}) | Implicitly creates myColl if it does not exist |
| db.myColl.drop() | Delete the collection and its indexes; returns true if it existed |
| db.myColl.renameCollection(new) | Rename a collection within the same database |
| db.myColl.countDocuments({}) | Count documents matching a filter |
| validator option | Attach JSON Schema rules so inserts must match a shape |
| capped option | Fixed-size collection that overwrites the oldest documents; use only for special cases |
Key Takeaways
Use db.createCollection() only when you need options. Otherwise just insert and let MongoDB create the collection for you.
Frequently Asked Questions
Do I need to create a collection before inserting?
No. Inserting into a collection that does not exist creates it automatically.
How do I list all collections?
Use show collections in mongosh, or db.getCollectionNames() to get an array.
How do I delete a collection?
Call db.collectionName.drop(). It returns true when the collection existed and was removed.
What is a capped collection?
A fixed-size collection that keeps insertion order and automatically overwrites the oldest documents when full. It is useful for simple rolling logs.
Can documents in one collection have different fields?
Yes, unless you add schema validation. Most applications still keep documents in a collection broadly similar.
Is a collection the same as a table?
It is the closest equivalent, but collections do not enforce columns and typically hold documents with embedded data instead of requiring joins.
Next: MongoDB CRUD Operations
Continue the MongoDB learning path.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
8 people found this page helpful
