mongosh Essentials
mongosh for MongoDB debugging.
Connecting
mongosh "mongodb://user:pass@host:27017/db". Replica set: comma-separate hosts and add replicaSet=rs0.
Atlas connections use srv records: mongodb+srv://cluster.mongodb.net/db. The driver resolves the seed list automatically.
Default port 27017. Authentication usually required in production; configure per environment in your shell rc or use a secrets manager.
Inspecting state
show dbs lists databases. use mydb switches context. show collections lists collections in the current db.
db.collection.findOne() returns the first document. Useful for sanity-checking schema without drowning in output.
db.collection.countDocuments() for accurate counts. estimatedDocumentCount() is faster but uses metadata that can drift.
Query patterns
db.users.find({email: 'foo@bar.com'}). Equality match. Add .pretty() for readable output.
db.orders.find({total: {$gt: 100}}).sort({date: -1}).limit(10). Range query, sort, limit. Standard production debugging shape.
db.collection.aggregate([{$match: ...}, {$group: ...}, {$sort: ...}]). Aggregation pipeline. Rich; complex; powerful.
Performance debugging
db.collection.explain('executionStats').find(query). Shows query plan, index usage, document scan count. The first stop for slow queries.
db.currentOp() lists in-flight operations. db.killOp(opid) terminates a runaway query. Useful when an analytics query is locking primary.
db.serverStatus() returns instance state: connections, locks, replication lag, memory. The MongoDB equivalent of show full processlist plus pg_stat_activity.
Admin commands
rs.status() shows replica set state. Members, lag, last heartbeat. The first thing to check during replication issues.
db.runCommand({ping: 1}). Lightweight liveness check. Used in health checks and load balancer probes.
use admin; db.auth(...) elevates privileges where role-based access requires it. Treat admin sessions as privileged; don't leave them open.