MongoDB Shell Commands
Essential commands for database operations
⌨️ What are Shell Commands?
MongoDB shell commands are built-in functions that help you manage databases, collections, and documents. These commands provide quick access to common operations and administrative tasks for efficient database management.
// Quick database information
db.stats()
Command Categories
Database Commands
Manage databases and info
Collection Commands
Work with collections
Document Commands
Query and modify documents
Admin Commands
Administrative operations
🔹 Database Commands
Commands for managing and inspecting databases. These are your primary tools for database-level operations, providing information and control over your MongoDB instances.
🔸 Basic Database Operations
// Show all databases
show dbs
// Switch to database (creates if doesn't exist)
use myDatabase
// Show current database
db
// Get current database name
db.getName()
// Drop current database
db.dropDatabase()
// Get database statistics
db.stats()
// Get server version
db.version()
Output:
admin 40.00 KiB config 12.00 KiB local 72.00 KiB myDatabase 256.00 KiB switched to db myDatabase myDatabase
🔸 Database Information
// Get detailed database stats
db.stats()
// Get server status
db.serverStatus()
// Get server build info
db.serverBuildInfo()
// Get current operations
db.currentOp()
// Get profiling level
db.getProfilingLevel()
// Set profiling level (0=off, 1=slow, 2=all)
db.setProfilingLevel(1, { slowms: 100 })
🔹 Collection Commands
Manage collections within your database. Collections are groups of documents, similar to tables in relational databases, and these commands help you create, modify, and inspect them.
🔸 Collection Management
// Show all collections
show collections
// Create collection
db.createCollection("users")
// Create collection with options
db.createCollection("products", {
capped: true,
size: 5242880,
max: 5000
})
// Rename collection
db.users.renameCollection("customers")
// Drop collection
db.users.drop()
// Get collection statistics
db.users.stats()
🔸 Collection Information
// Count documents in collection
db.users.countDocuments()
// Count with filter
db.users.countDocuments({ age: { $gt: 18 } })
// Get collection size
db.users.dataSize()
// Get storage size
db.users.storageSize()
// Get total index size
db.users.totalIndexSize()
// Validate collection
db.users.validate()
🔹 Index Commands
Create and manage indexes to improve query performance. Indexes are crucial for fast data retrieval, especially with large collections and complex queries.
🔸 Index Operations
// Show all indexes
db.users.getIndexes()
// Create single field index
db.users.createIndex({ email: 1 })
// Create compound index
db.users.createIndex({ lastName: 1, firstName: 1 })
// Create unique index
db.users.createIndex({ email: 1 }, { unique: true })
// Create text index
db.articles.createIndex({ content: "text" })
// Drop specific index
db.users.dropIndex("email_1")
// Drop all indexes (except _id)
db.users.dropIndexes()
// Rebuild indexes
db.users.reIndex()
🔸 Index Analysis
// Explain query execution
db.users.find({ age: 25 }).explain("executionStats")
// Get index statistics
db.users.aggregate([{ $indexStats: {} }])
// Check if index is used
db.users.find({ email: "[email protected]" }).explain()
🔹 Query Commands
Advanced query operations and modifiers for precise data retrieval:
🔸 Query Modifiers
// Limit results
db.users.find().limit(10)
// Skip documents
db.users.find().skip(20)
// Sort results
db.users.find().sort({ age: -1 })
// Project specific fields
db.users.find({}, { name: 1, email: 1, _id: 0 })
// Count results
db.users.find({ age: { $gt: 18 } }).count()
// Distinct values
db.users.distinct("country")
// Find and modify
db.users.findAndModify({
query: { name: "John" },
update: { $set: { age: 26 } },
new: true
})
🔸 Aggregation Commands
// Basic aggregation
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } }
])
// Count by group
db.users.aggregate([
{ $group: { _id: "$country", count: { $sum: 1 } } }
])
// Calculate average
db.products.aggregate([
{ $group: { _id: "$category", avgPrice: { $avg: "$price" } } }
])
🔹 User Management Commands
Create and manage database users with specific roles and permissions:
// Show users
show users
// Create user
db.createUser({
user: "appUser",
pwd: "securePassword123",
roles: [
{ role: "readWrite", db: "myDatabase" }
]
})
// Create admin user
db.createUser({
user: "admin",
pwd: "adminPassword123",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" }
]
})
// Update user password
db.changeUserPassword("appUser", "newPassword456")
// Grant role to user
db.grantRolesToUser("appUser", [
{ role: "dbAdmin", db: "myDatabase" }
])
// Revoke role from user
db.revokeRolesFromUser("appUser", [
{ role: "dbAdmin", db: "myDatabase" }
])
// Drop user
db.dropUser("appUser")
// Get user info
db.getUser("appUser")
🔹 Utility Commands
Helpful commands for debugging and information:
Common Utility Commands:
- help - Show help information
- db.help() - Database method help
- db.collection.help() - Collection method help
- show logs - Show available logs
- show log global - Show recent log entries
- cls - Clear the shell screen
- exit - Exit the shell
// Get help
help
// Database methods help
db.help()
// Collection methods help
db.users.help()
// Show recent logs
show log global
// Get hostname
db.hostInfo()
// Get command history
db.adminCommand({ getLog: "global" })
// Print in JSON format
printjson(db.users.findOne())
🔹 Bulk Operations
Perform multiple operations efficiently in a single batch:
// Initialize bulk operation
var bulk = db.users.initializeUnorderedBulkOp()
// Add operations
bulk.insert({ name: "Alice", age: 25 })
bulk.insert({ name: "Bob", age: 30 })
bulk.find({ name: "Charlie" }).update({ $set: { age: 35 } })
bulk.find({ age: { $lt: 18 } }).remove()
// Execute bulk operation
bulk.execute()
// Ordered bulk operation
var orderedBulk = db.users.initializeOrderedBulkOp()
orderedBulk.insert({ name: "David", age: 28 })
orderedBulk.find({ name: "Eve" }).updateOne({ $inc: { age: 1 } })
orderedBulk.execute()