MongoDB Collections
Understanding collections and how to work with them
📚 What are Collections?
Collections in MongoDB are groups of documents, similar to tables in relational databases. They store related data together and are created automatically when you insert your first document into them.
// Create a collection by inserting data
db.customers.insertOne({ name: "Sarah", age: 28 })
// Collection 'customers' is now created
Collection Basics
Collections are flexible containers for documents. Unlike SQL tables, collections don't enforce a strict schema, allowing documents with different structures to coexist in the same collection.
Auto Creation
Created when first document inserted
db.orders.insertOne({})
View Collections
List all collections in database
show collections
Explicit Creation
Create collection manually
db.createCollection("users")
Drop Collection
Delete entire collection
db.users.drop()
🔹 Creating Collections Implicitly
The easiest way to create a collection is by inserting a document. MongoDB creates the collection automatically:
// Switch to database
use storeDB
// Insert document (creates 'products' collection)
db.products.insertOne({
name: "Laptop",
price: 999,
brand: "TechCo"
})
// View all collections
show collections
Output:
products
🔹 Creating Collections Explicitly
You can create an empty collection using the createCollection() method:
// Create empty collection
db.createCollection("employees")
// Create collection with options
db.createCollection("logs", {
capped: true,
size: 5242880, // 5MB
max: 5000 // max documents
})
// Verify collection exists
show collections
Output:
employees
logs
🔹 Viewing Collections
Use these commands to see collections in your current database:
// Show all collections
show collections
// Alternative command
show tables
// Get collection names as array
db.getCollectionNames()
Output:
[ "customers", "orders", "products" ]
🔹 Collection Information
Get detailed information about a collection:
// Get collection statistics
db.customers.stats()
// Count documents in collection
db.customers.countDocuments()
// Check if collection exists
db.getCollectionNames().includes("customers")
Output:
Document count: 150
Collection exists: true
🔹 Dropping Collections
Remove a collection and all its documents permanently:
// Drop a collection
db.oldData.drop()
// Verify it's gone
show collections
Output:
⚠️ Collection 'oldData' dropped
Warning:
Dropping a collection is permanent and cannot be undone. All documents in the collection will be deleted.
🔹 Collection Naming Rules
Follow these guidelines when naming collections:
- Start with letter or underscore: Not a number
- No special characters: Avoid $, spaces, null characters
- Max length: 120 characters (including database name)
- Case sensitive: "Users" and "users" are different
- Use plural names: "users", "products", "orders"
// Good collection names
db.users.insertOne({})
db.product_reviews.insertOne({})
db.orderHistory.insertOne({})
// Bad collection names (avoid)
db.123users.insertOne({}) // starts with number
db.user data.insertOne({}) // has space
db.$special.insertOne({}) // starts with $
🔹 Complete Example
Here's a practical example of working with collections:
// Switch to database
use blogDB
// Create multiple collections
db.createCollection("posts")
db.createCollection("comments")
db.createCollection("users")
// Add data to collections
db.posts.insertOne({
title: "Getting Started with MongoDB",
content: "MongoDB is a NoSQL database...",
author: "Jane Doe"
})
db.users.insertOne({
username: "janedoe",
email: "[email protected]"
})
// View all collections
show collections
// Count documents
db.posts.countDocuments()
db.users.countDocuments()
Output:
comments
posts
users
Posts: 1, Users: 1