Get Started Free

How to connect to MongoDB from the command line

Connect to MongoDB from the terminal with mongosh: connection strings, auth, Docker, and scripting with --eval, --file and --json without the usual traps.

Updated November 12, 2026 ยท Tested on MongoDB 7.0.45, mongosh 2.9.2 (and 2.13 inside the mongo:7 Docker image)

Quick Answer

Run mongosh with a connection string. With no arguments it connects to localhost:27017:

mongosh                                             # localhost:27017, database "test"
mongosh "mongodb://localhost:27017/shop"            # a specific database
mongosh "mongodb://app@db.example.com:27017/shop?authSource=admin"   # prompts for the password
mongosh "mongodb+srv://app@cluster0.abcde.mongodb.net/shop"          # Atlas

Leave the password out of the string and mongosh asks for it, so it doesn't end up in your shell history.

Connection string or flags

Everything can go in one URI, or you can use separate flags. These two connect the same way:

mongosh "mongodb://app@db.example.com:27017/shop?authSource=admin"
mongosh --host db.example.com --port 27017 -u app --authenticationDatabase admin shop
FlagURI equivalentNotes
--host h --port pmongodb://h:pmongosh turns these into a URI with directConnection=true added
-u / --usernameapp@Omit -p to be prompted
--authenticationDatabase admin?authSource=adminThe database the user was created in
--tls?tls=trueAtlas and +srv strings turn this on for you
database name (last argument)/shopAlso becomes the default authSource, see below

Inside the shell, db.getMongo()._uri prints the exact connection string mongosh built, which is the quickest way to check what your flags turned into.

In VisuaLeaf

Save the connection once in VisuaLeaf

If you keep retyping the same URI, save it as a connection instead. In VisuaLeaf's Connection Manager, click New Connection, paste your mongodb:// or mongodb+srv:// string into Paste Connection String and click Auto-Fill. It fills the Server, Authentication, SSL, SSH and Options tabs from the string.

Test Connection then checks network connectivity, authentication, the TLS handshake and database access step by step. That tells you which part failed, instead of a 30-second wait that ends in a generic timeout. Export to URL turns the saved settings back into a connection string for your scripts.

VisuaLeaf connection form with the Paste Connection String box, Auto-Fill button, Server, Authentication, SSL, SSH and Options tabs, and Test Connection and Export to URL buttons
The connection form: paste a URI, auto-fill, test, then save.

When you still want a shell, right-click the connection and choose Open MongoDB Shell. Results come back in Tree, Table or BSON view rather than as text. See the Connection Manager docs.

Logging in: authSource is the usual problem

A MongoDB user belongs to one database, usually admin. If you don't say which, mongosh authenticates against the database in the connection string, and you get a bare Authentication failed. that looks exactly like a wrong password.

# fails: authenticates against "shop", but the user lives in "admin"
mongosh "mongodb://app:secret@localhost:27017/shop"

# works
mongosh "mongodb://app:secret@localhost:27017/shop?authSource=admin"
mongosh -u app --authenticationDatabase admin shop

Special characters in a password (@ : / ? # %) must be percent-encoded in a URI, so p@ss becomes p%40ss. Using -u and the password prompt avoids encoding entirely.

For a full diagnosis of login errors, including how to read the server log to tell a wrong password from a wrong authSource, see Authentication failed.

Running commands without opening the shell

For scripts, cron jobs and CI, run a command and exit:

# one expression; its value is printed
mongosh --quiet "mongodb://localhost:27017/shop" --eval 'db.orders.countDocuments()'

# machine-readable output: note the = and the toArray()
mongosh --quiet --json=relaxed "mongodb://localhost:27017/shop" \
  --eval 'db.orders.find({ status: "paid" }).limit(100).toArray()' > paid.json

# a script file
mongosh --quiet "mongodb://localhost:27017/shop" --file report.js

# health check for a shell script
if mongosh --quiet "mongodb://localhost:27017" --eval 'db.adminCommand({ ping: 1 }).ok' >/dev/null 2>&1; then
  echo up
fi

--quiet drops the startup banner. --json=relaxed prints dates as {"$date": ...} and numbers as plain JSON; --json=canonical keeps every type explicit ({"$numberInt": "1"}), which round-trips exactly.

What we found testing this

Every item below was run on MongoDB 7.0 with mongosh 2.9.2. Most of these break scripts silently, which is why they're worth knowing.

  • --eval on a cursor prints only the first 20 documents. On a 30-document collection, --eval 'db.x.find()' printed 20 results and then Type "it" for more, with exit code 0. Redirected to a file, you lose the rest without any error. Add .toArray(), or raise the limit with config.set("displayBatchSize", 1000).
  • --file doesn't print the last value; --eval does. A file ending in db.t.countDocuments() printed nothing for the count. Use print() or printjson() in script files.
  • --json has traps. --json without = swallowed the next argument (the URI) and failed with --json can only have the values relaxed, canonical. And --json=relaxed on a cursor, without .toArray(), dumped a BSONError: Converting circular structure to EJSON stack trace.
  • Exit codes.
SituationExit code
Connection refused (fails in under 1 s)1
Wrong password1
throw in --eval or a --file (the rest of the file doesn't run)1
A server error, e.g. an invalid operator1
quit(3)3
process.exitCode = 40: ignored, use quit(n)
  • An unreachable host waits 30 seconds, even with --host. mongosh adds serverSelectionTimeoutMS=2000 to the URI it builds, yet a host that never answers still took 30.97 s, ending in Socket 'connect' timed out after 30000ms (connectTimeoutMS: 30000). For a fast health check, add ?connectTimeoutMS=2000&serverSelectionTimeoutMS=2000 to the URI: the same unreachable host then failed in 3.7 s. A refused connection fails in about 0.9 s either way.
  • The database name decides where you authenticate. mongosh -u root -p ... with no database logged in, because authentication fell back to admin. The same command with mydb on the end failed with Authentication failed., because the database name became the authSource. Adding --authenticationDatabase admin fixed it.

Connecting to MongoDB in Docker

# from your machine, through the published port
docker run -d --name mongo -p 27017:27017 mongo:7
mongosh "mongodb://localhost:27017"

# from inside the container (no install needed on your machine)
docker exec -it mongo mongosh

# a container started with MONGO_INITDB_ROOT_USERNAME / _PASSWORD
docker exec -it mongo mongosh -u root -p --authenticationDatabase admin

The official mongo:7 image ships mongosh (2.13 in our test) but not the old mongo shell. If you connect without credentials to a container that has a root user, the connection itself succeeds, and the first command fails with Command listDatabases requires authentication. Connecting isn't the same as logging in.

mongosh vs the old mongo shell

The legacy mongo shell was removed in MongoDB 6.0. Most commands carry over to mongosh; these are the differences that change results:

Behaviormongosh
Whole numbers like 1Stored as 32-bit int (we checked with $type). The old shell stored them as double.
DBQuery.shellBatchSizeStill works but prints a deprecation warning. Use config.set("displayBatchSize", n).
Startup script~/.mongoshrc.js (not .mongorc.js). In our test it wasn't loaded for --eval runs. --norc skips it explicitly.
Output formattingTypes print as ISODate('...'), Long('5'). Use --json for anything a program will parse.

Frequently Asked Questions

How do I connect to MongoDB from the command line?

Install mongosh and run mongosh "mongodb://host:27017/dbname". With no arguments it connects to localhost:27017. Add -u username and it prompts for the password.

Why does mongosh say Authentication failed when the password is right?

Usually the authSource. Users are normally created in admin, so add ?authSource=admin to the URI or --authenticationDatabase admin to the command.

How do I run a MongoDB query from a bash script?

Use mongosh --quiet --eval with the connection string. Add .toArray() to find() so you get every result, not just the first 20, and --json=relaxed if another program parses the output. Use quit(n) to set the exit code.

Is the mongo command still available?

No. The legacy mongo shell was removed in MongoDB 6.0 and is not in the official Docker images. Use mongosh.

How do I connect to MongoDB Atlas from the terminal?

Copy the mongodb+srv:// connection string from the Atlas Connect dialog and run mongosh with it. Your IP must be on the cluster's access list, or the connection times out.

VisuaLeaf

Save your connections instead of retyping them

VisuaLeaf's connection manager keeps local, Docker and Atlas connections with their auth settings, and its built-in mongosh shows results as a table, tree or JSON instead of 20 lines at a time.