MongoDB Databases & Collections
Databases in MongoDB
A MongoDB server can host multiple databases. Each database has its own set of collections and is isolated from others. MongoDB creates a database automatically the first time you insert data into it — there is no explicit CREATE DATABASE command needed.
// List all databases (only shows databases with data)
show dbs
// Switch to a database (creates it on first write)
use myapp
// Show current database name
db
// Get database statistics
db.stats()
// Drop the current database (irreversible!)
db.dropDatabase()
// Copy a database (deprecated in newer versions — use mongodump/mongorestore)
// db.copyDatabase("source", "destination")
Collections in MongoDB
Collections are analogous to tables in relational databases. They hold groups of documents. Collections are created implicitly when you first insert a document, or explicitly using createCollection() when you need to set specific options like capped collections or validation rules.
use myapp
// Implicit creation — collection is created on first insert
db.users.insertOne({ name: "Alice" })
// Explicit creation with options
db.createCollection("products")
// List all collections in current database
show collections
// or
db.getCollectionNames()
// Get collection info (includes options and UUID)
db.getCollectionInfos({ name: "users" })
// Rename a collection
db.users.renameCollection("customers")
// Drop a collection (removes all documents and indexes)
db.products.drop()
// Get collection statistics
db.users.stats()
db.users.totalSize()
db.users.storageSize()
Capped Collections
Capped collections are fixed-size collections that automatically overwrite the oldest documents when the size limit is reached. They are ideal for logs, caches, and event streams where you only need the most recent data.
// Create a capped collection
// size: max bytes (required), max: max number of documents (optional)
db.createCollection("appLogs", {
capped: true,
size: 10485760, // 10 MB
max: 5000 // max 5000 documents
})
// Check if a collection is capped
db.appLogs.isCapped() // true
// Create a collection with a collation (language-specific sorting)
db.createCollection("articles", {
collation: { locale: "en", strength: 2 }
})
// Convert an existing collection to capped
db.runCommand({
convertToCapped: "logs",
size: 5242880 // 5 MB
})