mongosh, connection strings and tools
The shell is a full JavaScript environment. Learn how to connect, navigate, read cursors, script, and which companion tools exist.
- Write standard and SRV connection strings
- Use shell helpers: use, show, it, print
- Understand cursors and batching in the shell
- Know the database tools: mongodump, mongorestore, mongoexport, mongostat, mongotop
conceptThe concept
mongosh is a Node.js-based shell. Everything you type is JavaScript, plus a few helpers (use, show, it). Connect with a URI:
mongosh "mongodb://app:secret@db1:27017,db2:27017,db3:27017/shop?replicaSet=rs0&authSource=admin&tls=true" mongosh "mongodb+srv://cluster0.example.net/shop" # hosts and options come from DNS SRV/TXT records mongosh --host localhost --port 27017 -u admin --authenticationDatabase admin
Listing every replica-set member in the URI (or using SRV) lets the driver discover the topology and follow failovers. directConnection=true pins one host and disables discovery.
find() returns a cursor. The shell prints the first 20 documents and it fetches the next batch. In scripts you consume cursors with toArray(), forEach() or for...of.
whyWhy it matters
Most production troubleshooting happens in mongosh: checking rs.status(), reading db.currentOp(), running explain(), or fixing data with a careful update. Knowing the helpers and cursor behaviour makes you fast and safe.
| Tool | Use |
|---|---|
| mongodump / mongorestore | Logical backup and restore in BSON, optionally with the oplog for a consistent point |
| mongoexport / mongoimport | JSON or CSV export/import of one collection |
| mongostat | Per-second insert/query/update/delete counters, cache usage, queues |
| mongotop | Time spent reading and writing per collection |
| Compass | GUI: schema analysis, explain plans, index management |
Use caseReal-world scenario
On-call at 2 a.m.: mongosh into the primary, run db.currentOp({ secs_running: { $gt: 5 } }) to find a runaway query, check its planSummary, kill it with db.killOp(), then add the missing index during the day.
Try itExamples
Run and edit these in the interactive lesson.
db.getName()
db.version()
show collectionsdb.orders.find({}, { orderNo: 1, total: 1 }).limit(25)it in the Playground to see the next batch.const statuses = db.orders.distinct("status")
statuses.forEach(s => print(s.padEnd(10), db.orders.countDocuments({ status: s })))
db.orders.find({ total: { $gt: 3000 } }).toArray().map(o => o.orderNo)db.hello()
db.serverStatus().opcountersinternalsUnder the hood
The shell wraps the official Node.js driver, so it follows the same server selection, retry and connection pool rules as your application. Each statement you run is a separate command; a cursor keeps a server-side cursor id open (10 minutes idle timeout by default) until it is exhausted or closed.
Avoid / preferDo this, not that
mongosh "mongodb://admin:S3cret@db1:27017/shop"
mongosh "mongodb://db1:27017,db2:27017,db3:27017/shop?replicaSet=rs0&tls=true" \ --username admin # prompts for the password
A password in the connection string lands in shell history and is visible in the process list. Leave it out and mongosh prompts for it.
db.events.find().toArray() // 40 million documents
db.events.find({ type: "error" }, { ts: 1, type: 1 }).limit(20)toArray() pulls every document into the shell's memory. Filter, project and limit interactively; use mongoexport or mongodump for bulk extraction.
PitfallsCommon mistakes
- Connecting to one replica-set member with
directConnection=truein an application, which breaks automatic failover. - Calling
toArray()on a huge result in a script and running out of memory. Iterate the cursor instead. - Running write scripts against production without first running the same filter with
find()andcountDocuments().
LimitsWhen not to use it
mongosh is for interactive administration and small scripts. Business logic that runs on a schedule belongs in an application with a driver, proper error handling, retries and monitoring. For bulk export and import, mongoexport, mongodump and mongorestore are faster and resumable.
SecuritySecurity notes
mongosh keeps a history file. Its redactHistory setting (default remove) drops lines that look sensitive, such as createUser calls and connection strings with credentials, but do not rely on it: avoid typing secrets, and use passwordPrompt() in commands such as db.createUser({ user: "app", pwd: passwordPrompt(), roles: [...] }).
ChallengeTry it yourself
Return one document with the server version, the current database name and the number of collections in it.
Show one solution
({ version: db.version(), db: db.getName(), collections: db.getCollectionNames().length })InterviewQuestions you should be able to answer
What is the difference between mongodb:// and mongodb+srv:// URIs?
mongodb+srv:// looks up the host list from DNS SRV records and connection options (such as replicaSet, authSource) from a TXT record, and it enables TLS by default. mongodb:// lists hosts explicitly. Both let the driver discover the full topology.
How do you find and stop a long-running operation?
db.currentOp({ active: true, secs_running: { $gt: 10 } }) shows running operations with opid, namespace, planSummary and the command. db.killOp(opid) stops it. Prefer maxTimeMS on queries so they cannot run away in the first place.
QuizCheck your understanding
4 questions with instant feedback in the interactive lesson; a wrong answer goes into your review deck.