Creating Databases and Collections
Now that you understand documents, it's time to organize them. In MongoDB, documents live in collections, and collections live inside databases. This lesson covers creating, managing, and securing both.
1. Creating a Database
MongoDB uses a "create on first write" approach — a database isn't physically created until it has at least one collection with a document.
use ecommerceDB
db.products.insertOne({ name: "Wireless Mouse", price: 799 })
// Now ecommerceDB exists and appears in `show dbs`
2. Creating Collections
Collections can be created implicitly (on first insert) or explicitly with configuration options.
// Implicit creation
db.orders.insertOne({ orderId: 1001, total: 2499 })
// Explicit creation with options
db.createCollection("logs", {
capped: true,
size: 5242880, // 5MB max size
max: 5000 // Max 5000 documents
})
| Command | Purpose |
|---|---|
db.createCollection(name) | Explicitly create a collection |
show collections | List all collections |
db.collection.drop() | Delete a collection |
db.dropDatabase() | Delete the current database |
db.collection.renameCollection(newName) | Rename a collection |
3. Capped Collections
Capped collections are fixed-size collections that maintain insertion order and automatically overwrite the oldest documents once the size limit is reached — ideal for logs and caches.
4. User Authorization and Access Control
MongoDB uses role-based access control (RBAC) to manage who can create, read, or modify databases and collections.
use admin
db.createUser({
user: "appUser",
pwd: "strongPassword123",
roles: [
{ role: "readWrite", db: "ecommerceDB" }
]
})
| Built-in Role | Access Level |
|---|---|
read | Read-only access to a database |
readWrite | Read and write access |
dbAdmin | Schema and index administration |
userAdmin | Manage users and roles |
root | Full superuser access (all databases) |
readWrite on their specific database, never root.
5. Databases and Collections Checklist
- ✅ Understand implicit vs explicit creation
- ✅ Know how capped collections work
- ✅ Create a database user with a scoped role
- ✅ Practice dropping and renaming collections safely
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.