Create and Drop Collections
Learn how to create, list, and drop collections in MongoDB. Understand implicit vs explicit collection creation, capped collections, schema validation, and how collections organize your documents.
Collections in MongoDB are the equivalent of tables in relational databases. A collection holds a group of documents (records). Unlike SQL tables, collections don't enforce a fixed schema — documents within the same collection can have different fields and data types.
Implicit Collection Creation
Like databases, collections are created automatically when you insert data:
use blogApp
// This creates the "posts" collection automatically
db.posts.insertOne({ title: "Hello World" })
// The "comments" collection is created here
db.comments.insertOne({ text: "Great post!", postId: 1 })
Explicit Collection Creation
You can also create collections explicitly with options:
// Create a simple collection
db.createCollection("users")
// Create with options
db.createCollection("logs", {
capped: true,
size: 10485760, // 10 MB max size
max: 5000 // Maximum 5000 documents
})
Capped Collections
Capped collections are fixed-size collections that automatically overwrite the oldest documents when the size limit is reached. They're perfect for logs, caches, and event streams:
// Create a capped collection for application logs
db.createCollection("appLogs", {
capped: true,
size: 52428800, // 50 MB
max: 100000 // Max 100K documents
})
// Insert logs — oldest will be auto-removed when limit is reached
db.appLogs.insertOne({
level: "info",
message: "User logged in",
timestamp: new Date()
})
Key characteristics of capped collections:
- Insertion order is preserved (natural ordering)
- Very fast writes — no index overhead for ordering
- Cannot delete individual documents (only drop the entire collection)
- Cannot grow beyond the specified size
- Great for: logs, real-time analytics, message queues
Schema Validation
While MongoDB is schema-flexible, you can enforce rules on what documents can be inserted:
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price", "category"],
properties: {
name: {
bsonType: "string",
description: "Product name — required, must be a string"
},
price: {
bsonType: "number",
minimum: 0,
description: "Price — required, must be non-negative"
},
category: {
bsonType: "string",
enum: ["electronics", "clothing", "books", "food"],
description: "Category — must be one of the allowed values"
},
inStock: {
bsonType: "bool"
}
}
}
},
validationLevel: "strict", // "strict" or "moderate"
validationAction: "error" // "error" or "warn"
})
// This succeeds
db.products.insertOne({
name: "Laptop",
price: 999.99,
category: "electronics",
inStock: true
})
// This fails — missing required "category" field
db.products.insertOne({
name: "Unknown Item",
price: 50
})
// This fails — price is negative
db.products.insertOne({
name: "Bad Product",
price: -10,
category: "books"
})
Listing Collections
// Show all collections in the current database
show collections
// Programmatic way with more details
db.getCollectionNames()
// Get detailed info about all collections
db.getCollectionInfos()
Renaming a Collection
// Rename "posts" to "articles"
db.posts.renameCollection("articles")
// Verify
show collections
Dropping a Collection
// Drop a collection — permanently deletes all documents and indexes
db.comments.drop()
// Returns true if the collection existed, false otherwise
Warning: Like dropping a database, this is irreversible. All documents and indexes in the collection will be permanently deleted.
Collection Naming Rules
- Cannot be empty
- Cannot contain the null character
- Cannot start with
system.(reserved prefix) - Should not contain the
$character - Maximum length: 120 bytes (including database name and dot separator)
- Convention: use plural nouns in camelCase (e.g.,
users,blogPosts,orderItems)
Practical Example
Let's set up collections for an e-commerce database:
use ecommerce
// Products with schema validation
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "price"],
properties: {
name: { bsonType: "string" },
price: { bsonType: "number", minimum: 0 }
}
}
}
})
// Orders — regular collection
db.createCollection("orders")
// Activity log — capped at 100MB
db.createCollection("activityLog", {
capped: true,
size: 104857600
})
// Verify all collections
show collections
What's Next
You now understand how to create and manage collections with various options. In the next episode, we'll start inserting documents into collections — learning insertOne(), insertMany(), and how MongoDB handles document IDs.