Quick Reference

Cheatsheets

Practical command references for Linux, networking, servers, containers, databases, and more.

Cheatsheet#mongodb-cheatsheet

MongoDB Command Cheatsheet

Installation

Debian / Ubuntu (official)

wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt update && sudo apt install mongodb-org

MongoDB is a source-available cross-platform document-oriented database program.

Database Operations

Database Commands

show dbs                                 // List all databases
use database_name                        // Switch/create database
db                                       // Show current database
db.dropDatabase()                        // Delete current database
db.stats()                               // Database statistics

Collection Operations

show collections                         // List collections
db.createCollection("users")             // Create collection
db.users.drop()                          // Delete collection
db.users.renameCollection("customers")   // Rename collection

CRUD Operations

Insert Documents

db.users.insertOne({ name: "John", age: 30 })
db.users.insertMany([
  { name: "Alice", age: 25 },
  { name: "Bob", age: 35 }
])

Find Documents

db.users.find()                          // All documents
db.users.find().pretty()                 // Formatted output
db.users.find({ age: 30 })               // Exact match
db.users.find({ age: { $gt: 25 } })      // Greater than
db.users.findOne({ name: "John" })       // First match

Update Documents

db.users.updateOne(
  { name: "John" },
  { $set: { age: 31 } }
)
db.users.updateMany(
  { age: { $lt: 25 } },
  { $set: { status: "young" } }
)
db.users.replaceOne(
  { name: "John" },
  { name: "John Doe", age: 31 }
)

Delete Documents

db.users.deleteOne({ name: "John" })
db.users.deleteMany({ age: { $lt: 25 } })
db.users.deleteMany({})                  // Delete all

Query Operators

Comparison

$eq, $ne, $gt, $gte, $lt, $lte, $in, $nin
 
db.users.find({ age: { $gte: 25, $lte: 35 } })
db.users.find({ status: { $in: ["active", "pending"] } })

Logical

db.users.find({
  $and: [{ age: { $gte: 25 } }, { status: "active" }]
})
db.users.find({
  $or: [{ age: { $lt: 25 } }, { age: { $gt: 35 } }]
})

Element

db.users.find({ email: { $exists: true } })
db.users.find({ age: { $type: "number" } })

Update Operators

Field Updates

$set, $unset, $inc, $mul, $rename, $min, $max
 
db.users.updateOne(
  { name: "John" },
  { $set: { age: 31 }, $inc: { score: 10 } }
)

Array Updates

$push, $pull, $addToSet, $pop
 
db.users.updateOne(
  { name: "John" },
  { $push: { tags: "mongodb" } }
)
db.users.updateOne(
  { name: "John" },
  { $addToSet: { tags: "database" } }
)

Projection & Sorting

Field Selection

db.users.find({}, { name: 1, age: 1 })   // Include
db.users.find({}, { password: 0 })       // Exclude
db.users.find({}, { _id: 0, name: 1 })   // Exclude _id

Sort & Limit

db.users.find().sort({ age: -1 })        // Descending
db.users.find().limit(10)
db.users.find().skip(20).limit(10)       // Pagination
db.users.countDocuments()

Indexes

Index Operations

db.users.createIndex({ email: 1 })       // Ascending
db.users.createIndex({ age: 1, name: 1 }) // Compound
db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex({ description: "text" })
db.users.getIndexes()
db.users.dropIndex("email_1")

Aggregation

Pipeline Stages

db.users.aggregate([
  { $match: { age: { $gte: 25 } } },
  { $group: { _id: "$status", count: { $sum: 1 } } },
  { $sort: { count: -1 } },
  { $limit: 10 }
])

Common Examples

// Count by field
db.users.aggregate([
  { $group: { _id: "$status", count: { $sum: 1 } } }
])
 
// Average
db.users.aggregate([
  { $group: { _id: null, avgAge: { $avg: "$age" } } }
])
 
// Unwind array
db.users.aggregate([
  { $unwind: "$tags" },
  { $group: { _id: "$tags", count: { $sum: 1 } } }
])
 
// Join collections
db.orders.aggregate([
  {
    $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "user"
    }
  }
])
db.articles.createIndex({ content: "text" })
db.articles.find({ $text: { $search: "mongodb" } })
db.articles.find({ $text: { $search: "\"exact phrase\"" } })

Administration

User Management

db.createUser({
  user: "admin",
  pwd: "password",
  roles: ["readWrite", "dbAdmin"]
})
db.getUsers()
db.dropUser("username")

Performance

db.users.find({ age: 30 }).explain()
db.setProfilingLevel(2)
db.system.profile.find()

Replication & Sharding

Replica Set Operations (rs.*)

// Initialize a replica set
rs.initiate()
 
// Add members
rs.add("mongodb1.example.com:27017")
rs.add("mongodb2.example.com:27017")
rs.add({ host: "mongodb3.example.com:27017", priority: 0, hidden: true })
 
// View replica set status and config
rs.status()        // Current state, health, and roles
rs.conf()          // Full replica set configuration
 
// Step down primary (for maintenance)
rs.stepDown(120)   // Step down for 120 seconds
rs.stepDown()      // Step down with default timeout (60s)
 
// Other useful replica set commands
rs.isMaster()      // Check if current node is primary
rs.printReplicationInfo()  // View oplog details
rs.slaveOk()       // Allow reads from secondary (legacy)

Sharding Operations (sh.*)

// Connect to mongos (the sharding router)
// mongos --configdb configReplSet/config1:27019,config2:27019,config3:27019
 
// Enable sharding on a database
sh.enableSharding("mydb")
 
// Shard a collection
sh.shardCollection("mydb.users", { "_id": "hashed" })             // Hashed shard key
sh.shardCollection("mydb.orders", { "userId": 1, "date": 1 })     // Compound shard key
sh.shardCollection("mydb.logs", { "_id": 1 })                     // Ranged shard key
 
// Shard management
sh.status()                                // View sharding status
sh.addShard("shard1/mongodb1:27018")       // Add a shard
sh.removeShard("shard1")                   // Remove a shard
sh.startBalancer()                         // Re-enable balancer
sh.stopBalancer()                          // Pause balancer
sh.disableBalancing("mydb.users")          // Disable balancing for a collection
sh.enableBalancing("mydb.users")           // Enable balancing for a collection

Key Sharding Concepts

// Zone-based sharding (tag-aware)
sh.addShardTag("shard1", "US-East")
sh.addShardTag("shard2", "EU-West")
sh.addTagRange("mydb.users", { country: "US" }, { country: "US" }, "US-East")

MongoDB CLI Tools

Backup & Restore (mongodump / mongorestore)

mongodump --db=mydb --out=/backup/         # Backup entire database
mongodump --uri="mongodb://user:pass@host:27017/mydb"  # Backup with connection string
mongodump --db=mydb --collection=users --out=/backup/  # Backup single collection
mongodump --db=mydb --gzip --archive=backup.gz         # Compressed archive backup
 
mongorestore --db=mydb /backup/mydb/                  # Restore database
mongorestore --drop --db=mydb /backup/mydb/           # Drop before restore
mongorestore --gzip --archive=backup.gz               # Restore from archive
mongorestore --uri="mongodb://user:pass@host:27017/mydb" /backup/mydb/

Export / Import (mongoexport / mongoimport)

mongoexport --db=mydb --collection=users --out=users.json        # Export to JSON
mongoexport --db=mydb --collection=users --csv --out=users.csv   # Export to CSV
mongoexport --db=mydb --collection=users --query='{"age": {$gt: 25}}' --out=filtered.json
 
mongoimport --db=mydb --collection=users --file=users.json       # Import from JSON
mongoimport --db=mydb --collection=users --file=users.csv --type=csv --headerline
mongoimport --db=mydb --collection=users --file=users.json --drop # Drop before import
mongoimport --uri="mongodb://user:pass@host:27017/mydb" --collection=users --file=users.json

Real-time Monitoring (mongostat / mongotop)

mongostat                          # Default output (1s interval)
mongostat 5                        # Every 5 seconds
mongostat --rowcount 10            # Stop after 10 rows
mongostat --uri="mongodb://user:pass@host:27017"  # Remote host
mongostat --discover               # Auto-discover replica set members
 
mongotop                           # Show read/write activity per collection
mongotop 5                         # Every 5 seconds
mongotop --locks                   # Include lock info
mongotop --uri="mongodb://user:pass@host:27017"

Best Practices

  1. Use indexes for frequently queried fields
  2. Use projection to limit returned fields
  3. Use aggregation pipeline for complex queries
  4. Monitor performance with explain()
  5. Enable authentication in production
  6. Regular backups are essential
  7. Avoid large documents (max 16MB)
  8. Use appropriate data types

Resources