mongosh Essentials
mongosh for MongoDB debugging.
Connecting
The connection step is the first source of confusion when an operator switches between deployments. The shape of the URI (single host, replica set, Atlas SRV) and the default port determine whether the shell finds the cluster at all; getting the connection right is the prerequisite for every command that follows.
- Single-host URI.
mongosh "mongodb://user:pass@host:27017/db"; the simplest connection shape for a standalone instance. - Replica set. Comma-separate hosts and add
replicaSet=rs0; the driver finds the primary via the seed list. - Atlas SRV.
mongodb+srv://cluster.mongodb.net/db; the driver resolves the seed list automatically. - Auth and port. Default port 27017; authentication usually required in production; per-environment config in shell rc or via a secrets manager.
Inspecting state
State inspection is the first step in any investigation. Listing databases and collections, sanity-checking schema with findOne, and getting accurate counts give the operator a map of the data before any specific query is written.
- show dbs / use / show collections. Database list, context switch, collection list; the navigation primitives.
- db.collection.findOne(). Returns the first document; sanity-checks schema without drowning in output.
- countDocuments() vs estimatedDocumentCount(). Accurate count vs fast metadata-based count; pick based on whether drift matters.
- Per-collection schema discovery. findOne plus countDocuments together give the operator the basic shape of the collection.
Query patterns
Production debugging usually shapes around equality matches, range queries with sort and limit, and aggregation pipelines for richer analysis. The three patterns cover most investigation paths; knowing each cold is the difference between a fast triage and a long fishing expedition.
- Equality match.
db.users.find({email: 'foo@bar.com'}); add.pretty()for readable output. - Range, sort, limit.
db.orders.find({total: {$gt: 100}}).sort({date: -1}).limit(10); the standard production debugging shape. - Aggregation pipeline.
db.collection.aggregate([{$match}, {$group}, {$sort}]); rich, complex, powerful. - Per-query projection. Project only needed fields; the smaller payload speeds large investigations.
Performance debugging
Performance debugging needs the right command for the right symptom. explain for slow queries, currentOp for in-flight investigation, serverStatus for instance-level state. The three together cover query-level, session-level, and instance-level visibility.
- explain('executionStats'). Query plan, index usage, document scan count; the first stop for slow queries.
- currentOp() / killOp(). In-flight operations and termination; useful when an analytics query is locking primary.
- serverStatus(). Instance state: connections, locks, replication lag, memory; the MongoDB equivalent of
show full processlistpluspg_stat_activity. - Per-incident performance trace. explain plus currentOp captured at incident time; supports postmortem reconstruction.
Admin commands
Admin commands cover replica set state, liveness probing, and privilege elevation. rs.status() is the first stop for replication issues; ping is the standard liveness probe; admin authentication should be treated as privileged and short-lived.
- rs.status(). 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(…). Privilege elevation where role-based access requires it; treat admin sessions as privileged.
- Per-session admin discipline. Don’t leave admin sessions open; close shells when the elevated work is done.