A compact, task‑oriented cheat sheet for day‑to‑day MongoDB work using mongosh and the core command‑line tools. Suitable for developers and sysadmins who already have MongoDB access and want fast recall, not installation steps.
Connect & Basics (mongosh)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Local default mongosh # Specific host/port mongosh "mongodb://db01.example.com:27017" # With user/password (SCRAM) mongosh "mongodb://user:pass@db01:27017/?authSource=admin" # X.509 (example) mongosh --tls --tlsCertificateKeyFile client.pem --host rs0/host1,host2,host3 # Show helper info help |
Prompt helpers
|
1 2 3 4 5 6 7 8 9 |
// Current DB db // List DBs show dbs // Switch DB (creates lazily) use appdb // List collections show collections |
Databases & Collections
|
1 2 3 4 5 6 7 8 9 10 11 12 |
// Create (implicit on first write) use appdb // Create collection with options /db.createCollection("events", { capped: false }) // Drop collection /db.events.drop() // Drop database /db.dropDatabase() |
Collection stats & size
|
1 2 3 4 |
/db.events.stats() /db.events.estimatedDocumentCount() /db.events.countDocuments({ type: "click" }) |
CRUD Essentials
Insert
|
1 2 3 |
/db.users.insertOne({ _id: 1, name: "Ada", plan: "pro" }) /db.users.insertMany([{ _id: 2, name: "Lin" }, { _id: 3, name: "Noor" }]) |
Find
|
1 2 3 4 5 |
/db.users.find({ plan: "pro" }) /db.users.findOne({ _id: 1 }) // Projection and sort /db.users.find({}, { name: 1, plan: 1, _id: 0 }).sort({ name: 1 }).limit(10) |
Update
|
1 2 3 |
/db.users.updateOne({ _id: 1 }, { $set: { plan: "enterprise" } }) /db.users.updateMany({ plan: "free" }, { $set: { plan: "pro" } }) |
Replace & Upsert
|
1 2 |
/db.users.replaceOne({ _id: 4 }, { _id: 4, name: "Kai" }, { upsert: true }) |
Delete
|
1 2 3 |
/db.users.deleteOne({ _id: 3 }) /db.users.deleteMany({ plan: { $exists: false } }) |
Query Operators (greatest hits)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Comparison { price: { $gt: 10, $lte: 50 } } // Logical { $and: [ { inStock: true }, { price: { $lt: 100 } } ] } // Element { email: { $exists: true } } // Array { tags: { $all: ["mongodb", "nosql"] } } { tags: "mongodb" } // any element equals { sizes: { $elemMatch: { w: { $gt: 10 }, h: { $lt: 20 } } } } // Regex { name: /doe/i } |
Aggregation Pipeline
|
1 2 3 4 5 6 7 |
/db.sales.aggregate([ { $match: { status: "A" } }, { $group: { _id: "$item", total: { $sum: "$amount" } } }, { $sort: { total: -1 } }, { $limit: 5 } ]) |
Common stages: $match, $project, $group, $sort, $limit, $lookup, $unwind, $addFields, $setWindowFields.
Faceted example
|
1 2 3 4 5 6 7 8 |
/db.products.aggregate([ { $match: { active: true } }, { $facet: { byBrand: [ { $group: { _id: "$brand", n: { $count: {} } } } ], priceStats: [ { $group: { _id: null, min: { $min: "$price" }, max: { $max: "$price" } } } ] } } ]) |
Indexing
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Single & compound /db.users.createIndex({ email: 1 }, { unique: true }) /db.orders.createIndex({ customerId: 1, createdAt: -1 }) // TTL (expire after 7 days) /db.sessions.createIndex({ lastSeen: 1 }, { expireAfterSeconds: 604800 }) // Text & wildcard /db.articles.createIndex({ content: "text", title: "text" }) /db.any.createIndex({ "$**": 1 }) // Inspect & drop /db.users.getIndexes() /db.users.dropIndex("email_1") |
Transactions (replica set or sharded)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const session = db.getMongo().startSession(); session.startTransaction(); try { session.getDatabase("billing").invoices.updateOne({ _id: 1 }, { $set: { paid: true } }); session.getDatabase("accounts").users.updateOne({ _id: 1 }, { $inc: { balance: -100 } }); session.commitTransaction(); } catch (e) { session.abortTransaction(); throw e; } finally { session.endSession(); } |
User & Role Management (admin)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Create user use admin /db.createUser({ user: "api", pwd: passwordPrompt(), // or "plain-text" roles: [ { role: "readWrite", db: "appdb" } ] }) // Update password /db.updateUser("api", { pwd: passwordPrompt() }) // List users/roles /db.getUsers() /db.getRoles({ showBuiltinRoles: false }) |
Admin & Diagnostics
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Server info & build /db.serverStatus() /db.isMaster() // or db.hello() in newer versions /version() // Current operations /db.currentOp() /db.killOp(opid) // Profiler /db.setProfilingLevel(1) // 0=off,1=slow,2=all /db.system.profile.find().sort({ ts: -1 }).limit(5) |
Replica Set
|
1 2 3 4 5 |
/rs.status() /rs.initiate() /rs.add("host2:27017") /rs.stepDown() |
Sharding (mongos)
|
1 2 3 4 |
/sh.status() /sh.enableSharding("appdb") /sh.shardCollection("appdb.events", { userId: 1, ts: 1 }) |
Import/Export & Backup Tools (CLI)
BSON dump/restore
|
1 2 3 4 5 6 7 |
# Full dump (BSON + metadata) mongodump --uri "mongodb://user:pass@host/admin" --out /backups/$(date +%F) # Restore to another cluster date=$(date +%F) mongorestore --uri "mongodb://user:pass@newhost/admin" /backups/$date |
JSON/CSV import/export
|
1 2 3 4 5 6 7 8 |
# Export a query to JSON echo '{"plan":"pro"}' | mongoexport --uri "$URI" \ --collection users --db appdb --queryFile - --out users_pro.json # CSV import (upsert on key) mongoimport --uri "$URI" --db appdb --collection products \ --type csv --headerline --upsertFields sku --file products.csv |
Stats & monitoring
|
1 2 3 |
mongostat --rowcount 10 --uri "$URI" mongotop --locks --rowcount 5 --uri "$URI" |
Performance Tips (quick hits)
- Always index fields used in
$match, join keys for$lookup, and sort prefixes. - Prefer projections to reduce network & memory (
find({}, {field:1})). - Use bulkWrite for many small updates/inserts.
- Avoid unbounded
$lookupand$groupwithout cardinality controls; consider$merge.
Scripting Snippets (mongosh)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Pagination helper function page(coll, q={}, proj={}, sort={_id:1}, limit=20, after=null) { const filter = after ? { ...q, _id: { $gt: after } } : q; const docs = coll.find(filter, proj).sort(sort).limit(limit).toArray(); return { docs, next: docs.length ? docs[docs.length-1]._id : null }; } // Bulk upsert example const ops = [ { updateOne: { filter: { sku: "A1" }, update: { $set: { price: 10 } }, upsert: true } }, { updateOne: { filter: { sku: "B2" }, update: { $set: { price: 12 } }, upsert: true } } ]; db.products.bulkWrite(ops, { ordered: false }); |
BSON Types & ObjectId
|
1 2 3 4 5 6 7 |
// Generate ObjectId and extract timestamp const id = new ObjectId(); id.getTimestamp(); // Store dates properly /db.events.insertOne({ ts: new Date(), when: ISODate("2025-11-05T12:00:00Z") }) |
Environment & Auth Nuggets
|
1 2 3 4 5 6 |
# URI best practice: encode special chars in passwords export URI='mongodb://user:p%40ss%3Aword@host1,host2/appdb?replicaSet=rs0&authSource=admin' # Retryable writes & read prefs mongosh "$URI&retryWrites=true&readPreference=secondaryPreferred" |
Common One‑Liners
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Top 5 largest collections by data size (requires mongosh) mongosh "$URI" --eval ' db.getMongo().getDBNames().forEach(d=>{ const c = db.getSiblingDB(d).getCollectionInfos().map(i=>i.name); c.forEach(n=>{ const s = db.getSiblingDB(d).getCollection(n).stats(); print(`${d}.${n}\t${s.size}`) }) })' | sort -k2 -nr | head -5 # Count documents matching a criteria mongosh "$URI" --eval 'db.users.countDocuments({plan:"pro"})' |
Version Awareness
Shell helpers and server commands evolve. When in doubt, check db.version(), db.hello() vs db.isMaster(), and tool flags via --help on your installed version.




