mongosh is MongoDB’s interactive command-line shell for connecting to a deployment and working directly with its data. It is a JavaScript and Node.js read-eval-print loop (REPL): enter a command, inspect the result, and refine a query without writing an application. It can connect to Atlas clusters and local or remote self-hosted deployments. section 2.5 section 3.2
To start with an Atlas cluster:
- Install mongosh with `brew install mongosh`, or download it for Windows, Linux, or macOS. Check the installation with `mongosh --version`. section 2.5
- Retrieve your cluster’s connection string with `atlas clusters connectionStrings describe "MongoDB-in-Action"`. Use your own cluster name and the connection string returned for it. section 2.5
- Connect with `mongosh`, the connection string, and your database username; enter the password when prompted. Once connected, run `show dbs` to inspect the available databases. section 2.5
Listing 2.1 Connecting to a MongoDB deployment with mongosh
mongosh "mongodb+srv://mongodb-in-action.fpomkk.mongodb.net" \ --apiVersion 1 --username 'manning' Enter password: ************
This connection example supplies an Atlas connection string, API version, and username, then prompts for the password. Replace the sample connection string and username with your own. section 2.5
For a self-hosted server, use its `mongodb://` address instead. Authenticated deployments can also specify `--username`, `--password`, and `--authenticationDatabase`. Results typically appear as textual JSON; syntax highlighting, autocomplete, error messages, and contextual help support interactive work. section 3.2.2 section 3.2
Run a reusable status script
Save JavaScript in a `.js` file, connect with mongosh, and run `load("/scripts/mongodb-script.js")`. A status script can select the `admin` database, call `serverStatus()`, and print the server version, host, uptime, and open connections. Use `require()` to include a Node.js or npm module; install any external dependency, such as Day.js, before running the script. `load()` executes a file, while `require()` includes a module. section 3.2.5
mongosh is also useful for stepping through a multidocument transaction: start a session and transaction, perform operations, then commit or abort on error. This manual approach exposes the necessary steps, but error handling and retries must be managed explicitly; transactions are usually run through application drivers. section 8.4.2
An Atlas SQL interface is another connection target. Copy its connection string and connect with mongosh using `--tls` and `--username`; after authentication, you can execute SQL queries against that interface. section 18.2.2
