Installation & Setup
Install MongoDB
bash
1# Ubuntu / Debian (MongoDB 7.0)2curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \3 sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor4echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \5 sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list6sudo apt update7sudo apt install -y mongodb-org8
9# Fedora / RHEL10sudo tee /etc/yum.repos.d/mongodb-org-7.0.repo << 'EOF'11[mongodb-org-7.0]12name=MongoDB Repository13baseurl=https://repo.mongodb.org/yum/redhat/8/mongodb-org/7.0/x86_64/14gpgcheck=115enabled=116gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc17EOF18sudo dnf install -y mongodb-org19
20# macOS (Homebrew)21brew tap mongodb/brew22brew install mongodb-community@7.023brew services start mongodb-community@7.024
25# Verify26mongosh --version27mongod --versionStart & Connect
bash
1# Linux (systemd)2sudo systemctl start mongod3sudo systemctl enable mongod4sudo systemctl status mongod5
6# Connect with mongosh (modern shell — replaces mongo)7mongosh # Local default (localhost:27017)8mongosh "mongodb://localhost:27017"9mongosh -u admin -p password --authenticationDatabase admin10mongosh --host replica1:27017,replica2:27017,replica3:27017 --replicaSet myrs11mongosh "mongodb+srv://cluster0.example.mongodb.net/" --apiKey MV3...12
13# Legacy mongo shell (MongoDB < 5.0)14mongo # Deprecated — use mongoshShell Autocomplete
bash
1# mongosh has built-in autocompletion2# Press Tab for suggestions in the shellUseful Aliases
bash
1alias mg='mongosh'2alias mgadmin='mongosh -u admin -p --authenticationDatabase admin'Important Paths & Config Files
Configuration Files
bash
1# Linux2/etc/mongod.conf # Main config file3/etc/mongos.conf # Shard router config4
5# macOS (Homebrew)6/usr/local/etc/mongod.conf # Config file7/opt/homebrew/etc/mongod.conf # Apple Silicon8
9# Show config from within mongosh10db.adminCommand({getParameter: 1, auditAuthorizationSuccess: 1})Data & Log Paths
bash
1# Linux2/var/lib/mongodb/ # Data directory3/var/log/mongodb/ # Log directory4/var/log/mongodb/mongod.log # Server log5/var/run/mongodb/mongod.sock # Unix socket (if configured)6
7# macOS (Homebrew)8/usr/local/var/mongodb/ # Data directory9/usr/local/var/log/mongodb/ # Log directoryKey Configuration (mongod.conf)
yaml
1# /etc/mongod.conf2storage:3 dbPath: /var/lib/mongodb4 journal:5 enabled: true6 wiredTiger:7 engineConfig:8 cacheSizeGB: 2 # ~50% of RAM - (oplog + connections)9
10systemLog:11 destination: file12 path: /var/log/mongodb/mongod.log13 logAppend: true14 logRotate: reopen15
16net:17 port: 2701718 bindIp: 0.0.0.0 # Listen on all interfaces19 maxIncomingConnections: 6553620
21security:22 authorization: enabled # Enable auth (CRITICAL)23 # keyFile: /etc/mongodb/keyfile # For replica set auth24 # tls:25 # mode: requireTLS26 # certificateKeyFile: /etc/mongodb/ssl.pem27
28replication:29 replSetName: myrs30 oplogSizeMB: 10240 # 10GB oplog31
32sharding:33 clusterRole: shardsvr # For shard members34 # clusterRole: configsvr # For config serversDatabase Operations
Create & Drop Databases
javascript
1use mydb // Switch/create database (created on first write)2db.createCollection("users") // Create collection explicitly3show dbs // List all databases4show databases // Same5db // Show current database6db.dropDatabase() // Drop current database7db.getSiblingDB("other") // Switch to another database without useCollection Operations
javascript
1show collections // List collections in current db2db.createCollection("users") // Create collection3db.users.drop() // Drop collection4db.users.renameCollection("members") // Rename collection5db.users.stats() // Collection statistics6db.users.dataSize() // Collection data size7db.users.totalIndexSize() // Index size8db.users.storageSize() // Storage size including padding9db.collectionName.isCapped() // Check if capped collection10db.runCommand({convertToCapped: "events", size: 1073741824}) // Convert to cappedCRUD Operations
Insert
javascript
1// Insert single document2db.users.insertOne({3 name: "Alice",4 email: "alice@example.com",5 age: 30,6 address: { city: "Portland", state: "OR" },7 tags: ["admin", "active"],8 createdAt: new Date()9})10
11// Insert multiple documents12db.users.insertMany([13 { name: "Bob", email: "bob@example.com", age: 25 },14 { name: "Charlie", email: "charlie@example.com", age: 35 }15])16
17// Insert with ordered: false (continue on error)18db.users.insertMany([...], { ordered: false })19
20// Bulk write (insert, update, delete in one operation)21db.users.bulkWrite([22 { insertOne: { document: { name: "Dave" } } },23 { updateOne: { filter: { name: "Alice" }, update: { $set: { age: 31 } } } },24 { deleteOne: { filter: { name: "Bob" } } }25])Query (Read)
javascript
1// Find all documents2db.users.find()3db.users.find().pretty()4
5// Find with filter6db.users.find({ age: 30 })7db.users.find({ age: { $gt: 25 } }) // Greater than8db.users.find({ age: { $gte: 25, $lte: 40 } }) // Range9db.users.find({ tags: "admin" }) // Array contains10db.users.find({ "address.city": "Portland" }) // Nested field11db.users.find({ email: { $regex: /@example/ } }) // Regex12
13// Comparison operators14// $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin15db.users.find({ age: { $in: [25, 30, 35] } })16db.users.find({ tags: { $nin: ["inactive"] } })17
18// Logical operators19db.users.find({ $and: [{ age: { $gte: 25 } }, { age: { $lte: 40 } }] })20db.users.find({ $or: [{ name: "Alice" }, { name: "Bob" }] })21db.users.find({ $not: { age: { $lt: 25 } } })22db.users.find({ $nor: [{ age: 25 }, { age: 30 }] })23
24// Projection (select fields)25db.users.find({}, { name: 1, email: 1 }) // Include only name, email26db.users.find({}, { _id: 0, name: 1 }) // Exclude _id27db.users.find({}, { name: 1, email: 1 }).sort({ name: 1 }) // Ascending28db.users.find({}, { name: 1 }).sort({ age: -1 }) // Descending29
30// Limit and skip31db.users.find().limit(10)32db.users.find().skip(20).limit(10) // Pagination33db.users.find().sort({ age: 1 }).skip(10).limit(5)34
35// Count36db.users.countDocuments({ age: { $gte: 25 } })37db.users.estimatedDocumentCount() // Fast count (no filter)38
39// Find one40db.users.findOne({ name: "Alice" })41db.users.findOne({ name: "Alice" }, { email: 1 })42
43// Distinct44db.users.distinct("age")45db.users.distinct("address.city")Update
javascript
1// Update single document2db.users.updateOne(3 { name: "Alice" },4 { $set: { age: 31, "address.city": "Seattle" } }5)6
7// Update multiple documents8db.users.updateMany(9 { age: { $lt: 25 } },10 { $set: { status: "young" } }11)12
13// Replace entire document14db.users.replaceOne(15 { name: "Alice" },16 { name: "Alice", email: "alice@new.com", age: 31 }17)18
19// Update operators20db.users.updateOne({ name: "Alice" }, { $inc: { age: 1 } }) // Increment21db.users.updateOne({ name: "Alice" }, { $unset: { phone: "" } }) // Remove field22db.users.updateOne({ name: "Alice" }, { $push: { tags: "new" } }) // Add to array23db.users.updateOne({ name: "Alice" }, { $pull: { tags: "old" } }) // Remove from array24db.users.updateOne({ name: "Alice" }, { $addToSet: { tags: "vip" } }) // Add if not exists25db.users.updateOne({ name: "Alice" }, { $rename: { "phone": "mobile" } }) // Rename field26db.users.updateOne({ name: "Alice" }, { $min: { age: 28 } }) // Set if lower27db.users.updateOne({ name: "Alice" }, { $max: { age: 35 } }) // Set if higher28
29// Upsert (update or insert)30db.users.updateOne(31 { email: "new@example.com" },32 { $set: { name: "New User", age: 28 } },33 { upsert: true }34)35
36// Find and update (returns old or new document)37db.users.findOneAndUpdate(38 { name: "Alice" },39 { $inc: { age: 1 } },40 { returnDocument: "after" } // "before" (old) or "after" (new)41)Delete
javascript
1// Delete single document2db.users.deleteOne({ name: "Alice" })3
4// Delete multiple documents5db.users.deleteMany({ age: { $lt: 18 } })6
7// Delete all documents8db.users.deleteMany({})9
10// Find and delete (returns deleted document)11db.users.findOneAndDelete({ name: "Alice" })12
13// Delete many and return count14db.users.deleteMany({ status: "inactive" }).deletedCountAggregation Framework
Basic Pipeline
javascript
1// Aggregation pipeline (like SQL GROUP BY)2db.orders.aggregate([3 { $match: { status: "completed" } }, // Filter4 { $unwind: "$items" }, // Flatten array5 { $group: {6 _id: "$userId",7 totalSpent: { $sum: "$items.price" },8 avgOrderValue: { $avg: "$items.price" },9 orderCount: { $sum: 1 }10 }},11 { $sort: { totalSpent: -1 } }, // Sort12 { $limit: 10 }, // Limit13 { $project: { // Reshape output14 _id: 0,15 userId: "$_id",16 totalSpent: 1,17 avgOrderValue: { $round: ["$avgOrderValue", 2] }18 }}19])Common Stages
javascript
1// $match — filter documents2{ $match: { status: "active", age: { $gte: 25 } } }3
4// $group — group and aggregate5{ $group: {6 _id: "$department",7 count: { $sum: 1 },8 totalSalary: { $sum: "$salary" },9 avgSalary: { $avg: "$salary" },10 maxSalary: { $max: "$salary" },11 minSalary: { $min: "$salary" },12 employees: { $push: "$name" } // Collect into array13}}14
15// $project — reshape documents16{ $project: {17 name: 1,18 fullName: { $concat: ["$firstName", " ", "$lastName"] },19 ageInYears: "$age",20 _id: 021}}22
23// $addFields — add new fields without removing existing24{ $addFields: {25 fullName: { $concat: ["$firstName", " ", "$lastName"] },26 ageNextYear: { $add: ["$age", 1] }27}}28
29// $sort — sort results30{ $sort: { createdAt: -1 } } // -1 = descending, 1 = ascending31
32// $limit and $skip33{ $limit: 10 }34{ $skip: 20 }35
36// $unwind — flatten array37{ $unwind: "$tags" }38
39// $lookup — join with another collection (like SQL JOIN)40{ $lookup: {41 from: "orders",42 localField: "_id",43 foreignField: "userId",44 as: "orders"45}}46
47// $unwind after lookup to flatten48{ $unwind: "$orders" }49
50// $out — write results to a new collection51{ $out: "aggregated_results" }52
53// $merge — merge results into existing collection54{ $merge: { into: "summary", on: "_id", whenMatched: "replace" } }55
56// $facet — multiple aggregations in parallel57{ $facet: {58 byStatus: [59 { $group: { _id: "$status", count: { $sum: 1 } } }60 ],61 byAgeRange: [62 { $bucket: { groupBy: "$age", boundaries: [0, 25, 35, 50, 100] } }63 ]64}}65
66// $bucket — group into ranges67{ $bucket: {68 groupBy: "$age",69 boundaries: [0, 25, 35, 50, 100],70 default: "Other",71 output: { count: { $sum: 1 }, names: { $push: "$name" } }72}}73
74// $text — full-text search75{ $match: { $text: { $search: "keyword" } } }Accumulator Operators
| Operator | Description |
|---|---|
$sum | Sum of values |
$avg | Average of values |
$min / $max | Min / max value |
$push | Push values into array |
$addToSet | Push unique values into array |
$first / $last | First / last value in group |
$mergeObjects | Merge documents |
$count | Count of documents |
Indexes
Create Indexes
javascript
1// Single field index2db.users.createIndex({ email: 1 }) // Ascending3db.users.createIndex({ createdAt: -1 }) // Descending4
5// Compound index6db.users.createIndex({ lastName: 1, firstName: 1 })7
8// Unique index9db.users.createIndex({ email: 1 }, { unique: true })10
11// Sparse index (only index documents that have the field)12db.users.createIndex({ phone: 1 }, { sparse: true })13
14// TTL index (auto-delete documents after time)15db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })16
17// Text index (full-text search)18db.articles.createIndex({ title: "text", content: "text" })19
20// Hashed index (for hash-based sharding)21db.users.createIndex({ _id: "hashed" })22
23// Wildcard index (index all fields in subdocuments)24db.products.createIndex({ "attributes.$**": 1 })25
26// Background index (don't block other ops — MongoDB 4.2+ builds in background automatically)27db.users.createIndex({ email: 1 }, { background: true })28
29// Partial index (only index documents matching filter)30db.orders.createIndex(31 { status: 1 },32 { partialFilterExpression: { status: "active" } }33)34
35// Create multiple indexes36db.users.createIndexes([37 { email: 1 },38 { name: 1, age: -1 }39])Manage Indexes
javascript
1// List all indexes2db.users.getIndexes()3db.users.listIndexes()4
5// Drop index6db.users.dropIndex({ email: 1 })7db.users.dropIndex("email_1") // By index name8db.users.dropIndexes() // Drop all (except _id)9db.users.dropIndexes(["email_1", "name_1"]) // Drop specific indexes10
11// Analyze index usage12db.users.aggregate([{ $indexStats: {} }])13
14// Check index size15db.users.stats().indexSizesExplain Queries
javascript
1// Basic explain2db.users.find({ email: "alice@example.com" }).explain()3
4// Explain with details5db.users.find({ email: "alice@example.com" }).explain("executionStats")6
7// Full analyze8db.users.find({ email: "alice@example.com" }).explain("allPlansExecution")9
10// Key explain output fields:11// winningPlan.inputStage.stage — IXSCAN (index used) or COLLSCAN (full scan — BAD)12// executionStats.totalDocsExamined — documents scanned (lower = better)13// executionStats.executionTimeMillis — query timeUser Administration
Create & Manage Users
javascript
1// Create admin user (must be run with --auth or on authenticated connection)2use admin3db.createUser({4 user: "admin",5 pwd: "securePassword123",6 roles: [7 { role: "userAdminAnyDatabase", db: "admin" },8 { role: "readWriteAnyDatabase", db: "admin" },9 { role: "clusterAdmin", db: "admin" }10 ]11})12
13// Create application user14use mydb15db.createUser({16 user: "appuser",17 pwd: "appPassword123",18 roles: [19 { role: "readWrite", db: "mydb" }20 ]21})22
23// Create read-only user24db.createUser({25 user: "readonly",26 pwd: "readOnlyPass",27 roles: [28 { role: "read", db: "mydb" }29 ]30})31
32// Update user roles33db.updateUser("appuser", {34 roles: [35 { role: "readWrite", db: "mydb" },36 { role: "read", db: "logs" }37 ]38})39
40// Change password41db.changeUserPassword("appuser", "newPassword123")42
43// List users44db.getUsers()45db.getUser("appuser")46
47// Remove user48db.dropUser("appuser")49
50// Authenticate51db.auth("admin", "securePassword123")Built-In Roles
| Role | Description |
|---|---|
read | Read access to all non-system collections |
readWrite | Read and write access |
dbAdmin | Admin tasks (indexes, stats, repair) |
userAdmin | Create and manage users/roles |
clusterAdmin | Admin replica sets, sharding |
readAnyDatabase | Read on all databases |
readWriteAnyDatabase | ReadWrite on all databases |
userAdminAnyDatabase | User admin on all databases |
dbAdminAnyDatabase | DB admin on all databases |
root | Superuser (all roles) |
Replica Sets
Initialize & Manage
javascript
1// Initialize replica set (run on primary node)2rs.initiate({3 _id: "myrs",4 members: [5 { _id: 0, host: "replica1:27017", priority: 2 },6 { _id: 1, host: "replica2:27017", priority: 1 },7 { _id: 2, host: "replica3:27017", priority: 1, arbiterOnly: true }8 ]9})10
11// Check replica set status12rs.status()13rs.conf()14rs.isMaster() // Check if current node is primary15rs.printReplicationInfo() // Oplog info16rs.printSecondaryReplicationInfo() // Replica lag17
18// Add/remove members19rs.add("new-replica:27017")20rs.remove("old-replica:27017")21
22// Reconfigure (force reconfig if primary is down)23cfg = rs.conf()24cfg.members[2].priority = 125rs.reconfig(cfg, { force: true })26
27// Step down primary (force election)28rs.stepDown(60) // Step down for 60 seconds29
30// Freeze a node (prevent from becoming primary)31rs.freeze(60) // Freeze for 60 secondsRead Preference
javascript
1// Set read preference (on client or from shell)2db.users.find().readPref("secondaryPreferred") // Read from secondary3db.users.find().readPref("nearest") // Closest node4
5// In connection string6// mongodb://host1,host2,host3/?readPreference=secondaryPreferredSharding
Configure Sharding
javascript
1// Connect to mongos (shard router)2mongosh --host mongos-host:270173
4// Enable sharding on a database5sh.enableSharding("mydb")6
7// Shard a collection8sh.shardCollection("mydb.users", { userId: "hashed" }) // Hashed9sh.shardCollection("mydb.orders", { orderId: 1 }) // Ranged10
11// Check sharding status12sh.status()13sh.getBalancerState()14sh.isBalancerRunning()15sh.stopBalancer()16sh.startBalancer()17
18// Add shard19sh.addShard("replica1:27017")Backup & Restore
mongodump / mongorestore
bash
1# Backup entire database2mongodump --db mydb --out /backup/3
4# Backup specific collection5mongodump --db mydb --collection users --out /backup/6
7# Backup all databases8mongodump --out /backup/9
10# Backup with authentication11mongodump -u admin -p password --authenticationDatabase admin --db mydb --out /backup/12
13# Backup remote server14mongodump --host primary:27017 --db mydb --out /backup/15
16# Compressed backup17mongodump --gzip --db mydb --out /backup/18
19# Oplog backup (point-in-time)20mongodump --oplog --out /backup/oplog/21
22# Restore entire database23mongorestore --db mydb /backup/mydb/24
25# Restore specific collection26mongorestore --db mydb --collection users /backup/mydb/users.bson27
28# Restore with drop (replace existing data)29mongorestore --drop --db mydb /backup/mydb/30
31# Restore compressed backup32mongorestore --gzip --db mydb /backup/mydb/33
34# Restore all databases35mongorestore /backup/MongoDB Database Tools (recommended)
bash
1# These are faster than mongodump/mongorestore2# Install: https://www.mongodb.com/try/download/database-tools3
4# Export to CSV/JSON5mongoexport --db mydb --collection users --type=csv --fields=name,email,age --out users.csv6mongoexport --db mydb --collection users --out users.json7
8# Import from CSV/JSON9mongoimport --db mydb --collection users --type=csv --headerline --file users.csv10mongoimport --db mydb --collection users --file users.jsonPerformance Tuning
Monitor Performance
javascript
1// Server status2db.serverStatus()3db.serverStatus().connections // Connection info4db.serverStatus().opcounters // Operation counts5db.serverStatus().wiredTiger // Storage engine stats6db.serverStatus().mem // Memory usage7
8// Current operations9db.currentOp()10db.currentOp({ active: true, secs_running: { $gt: 5 } }) // Long-running ops11
12// Kill operation13db.killOp(<opId>)14
15// Database stats16db.stats()17db.stats().collections18db.stats().dataSize19db.stats().indexSize20db.stats().storageSize21
22// Collection stats23db.users.stats()24db.users.stats().indexSizesSlow Query Analysis
javascript
1// Enable profiling (Level 0=off, 1=slow ops, 2=all ops)2db.setProfilingLevel(1, { slowms: 100 }) // Log ops > 100ms3
4// View slow queries5db.system.profile.find().sort({ ts: -1 }).limit(10).pretty()6
7// Disable profiling8db.setProfilingLevel(0)9
10// Profile info11db.getProfilingStatus()Explain Plans
javascript
1// COLLSCAN = full collection scan (BAD — needs index)2// IXSCAN = index scan (GOOD)3// SORT = in-memory sort (BAD for large datasets)4
5db.users.find({ email: "test" }).explain("executionStats")6
7// Key metrics:8// totalDocsExamined — lower is better9// totalKeysExamined — lower is better10// nReturned — documents returned11// executionTimeMillis — query timeWiredTiger Cache
javascript
1// Check cache usage2db.serverStatus().wiredTiger.cache3
4// Key fields:5// "bytes currently in the cache" — current cache size6// "maximum bytes configured" — max cache size7// "bytes not belonging to page images in the cache" — overhead8
9// Cache hit ratio (should be > 95%)10// (bytes read into cache) / (bytes requested from disk)Useful Queries
Schema Introspection
javascript
1// Database stats2db.stats()3
4// Collection stats5db.users.stats()6
7// List all collections with sizes8db.getCollectionNames().map(c => ({9 collection: c,10 size: db.getCollection(c).stats().size,11 count: db.getCollection(c).countDocuments()12}))13
14// Document schema analysis (MongoDB 3.6+)15db.users.aggregate([{ $schema: { content: { $value: "$$ROOT" } } }])16
17// Find documents with missing fields18db.users.find({ phone: { $exists: false } })19
20// Find documents with wrong type21db.users.find({ age: { $not: { $type: "number" } } })22
23// Document size distribution24db.users.aggregate([25 { $project: { size: { $bsonSize: "$$ROOT" } } },26 { $group: {27 _id: null,28 avgSize: { $avg: "$size" },29 maxSize: { $max: "$size" },30 minSize: { $min: "$size" }31 }}32])Change Streams
javascript
1// Watch for changes (requires replica set or sharded cluster)2const changeStream = db.users.watch()3
4changeStream.on("change", (change) => {5 console.log(change)6})7
8// Watch with filter9const changeStream = db.users.watch([10 { $match: { "operationType": "insert" } }11])12
13// Watch entire database14const changeStream = db.getDatabase("mydb").watch()15
16// Watch entire cluster17const changeStream = db.getMongo().watch()Troubleshooting
bash
1# Connection refused2sudo systemctl status mongod3sudo systemctl start mongod4sudo cat /var/log/mongodb/mongod.log | tail -505
6# Authentication failed7mongosh -u admin -p password --authenticationDatabase admin8# Ensure auth is enabled in mongod.conf9# Ensure user exists in admin database10
11# Replica set issues12mongosh --eval "rs.status()"13# Check if primary is reachable from all secondaries14# Check clock synchronization (NTP)15
16# Disk space17db.stats().storageSize # Current storage18du -sh /var/lib/mongodb/ # On disk19
20# Corrupt data21mongod --dbpath /var/lib/mongodb --repair22
23# Lock contention24db.currentOp({ "lockStats.Writing": { $gt: 0 } })25
26# OOM killed27# Check system logs28sudo journalctl -u mongod -n 10029# Increase WiredTiger cache or system RAMOutput Formatting
mongosh
javascript
1// Pretty print2db.users.find().pretty()3
4// Toggle auto-pretty in mongosh5// Settings > shell > autoIteration = true (default)6
7// Custom output format8db.users.find().toArray().forEach(doc => printjson(doc))9
10// Count results11db.users.find().count()12
13// Export to file14const cursor = db.users.find()15const output = cursor.toArray()16require("fs").writeFile("/tmp/users.json", JSON.stringify(output, null, 2))17
18// Print to console19print("Total users:", db.users.countDocuments())20printjson(db.users.findOne({ name: "Alice" }))