Connect to MongoDB with mongosh

Learn how to connect to MongoDB using the mongosh shell. This tutorial covers the essential commands, connection strings, and common troubleshooting tips for developers.

Focus: connect to mongodb with mongosh shell

Sponsored

You've installed MongoDB, started the server, maybe even inserted a few documents — but every time you open a new terminal, you're staring at a blinking cursor, unsure of the exact incantation needed to get back into your database. The mongosh shell is your primary gateway to interacting with MongoDB, and fumbling with connection strings wastes time and breaks your flow. This lesson ends that struggle. You'll master mongosh connections — from the simple local default to full URI-based connections with authentication — and learn the critical flags and troubleshooting moves that separate a confident developer from a confused one.

The problem this lesson solves

Without a reliable way to connect, you can't do anything else in MongoDB. You might be able to start mongosh with no arguments, but that only works if your server is running on localhost:27017 with no authentication — a rare luxury in real projects. Sooner or later you'll face a remote cluster, a required username and password, or an SSL-only connection. Guessing at flags and URI formats leads to cryptic errors like MongoServerError: bad auth Authentication failed. or frustrating timeouts. This lesson gives you a repeatable, explicit process for connecting to any MongoDB instance, so you can spend your energy on queries, not on connection pain.

Core concept / mental model

Think of mongosh as a phone call to your database. The default call with no arguments dials a well-known local number (localhost:27017). But real-world calls need a full phone number — that's the connection string (URI). A URI contains everything the shell needs to reach the right server, authenticate, and route your commands.

A MongoDB connection string looks like this:

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

Break it down:

  • mongodb:// — the protocol (always present, or mongodb+srv:// for DNS-based host lists).
  • username:password@ — optional credentials, URL-encoded if they contain special characters.
  • host and port — where the server lives; default port is 27017.
  • /defaultauthdb — the authentication database (often admin); also the default database for your session if you don't use one.
  • ?options — query parameters like authSource, replicaSet, tls, or retryWrites.

The shell's job is to parse this string, negotiate the connection, and drop you into a prompt where every command targets that cluster. Once connected, you interact with databases, collections, and documents — but without a valid connection, none of that exists.

How it works step by step

Connecting with mongosh follows a simple flow:

  1. Locate the server — the hostname and port from the URI or defaults.
  2. Resolve the authentication — if credentials are given, mongosh authenticates against the specified authSource database (defaults to the database in the path or admin).
  3. Establish the session — a TCP connection is opened; TLS is used if tls=true or via mongodb+srv.
  4. Enter the interactive shell — you're now in a JavaScript REPL with global db and use helpers.
  5. Run commands — everything you type is a MongoDB command or JavaScript expression.

For a local instance, the default flow is automatic:

mongosh

This is equivalent to:

mongosh mongodb://localhost:27017

The shell prints a welcome banner and shows the default test database. From there, you can switch databases with use mydb and start working.

Using a connection string

For anything non-default, you pass the full URI as the first argument:

mongosh "mongodb://localhost:27017/mydb"

If you're using MongoDB Atlas or a cluster with multiple hosts, use the mongodb+srv scheme:

mongosh "mongodb+srv://cluster0.example.mongodb.net/mydb"

The +srv format automatically resolves available hosts, but it requires the mongodb+srv driver — it won't work with custom ports.

Adding authentication

When your server requires credentials, include them in the URI:

mongosh "mongodb://user:pass@localhost:27017/mydb?authSource=admin"

If your password contains characters like @ or :, URL-encode them (e.g., %40 for @).

Using flags for specific cases

mongosh provides command-line flags as an alternative to URI options. For example:

mongosh --host localhost --port 27017 --username admin --password secret --authenticationDatabase admin

This is verbose but highly readable, and it's often easier in scripts that build commands dynamically. You can mix flags and URI, but it's cleaner to stick to one style per command.

Hands-on walkthrough

Let's make this real. We'll spin up a local MongoDB with authentication and connect with mongosh using a URI.

Step 1: Start a secure MongoDB instance

For this demo, we'll start mongod with a tiny admin user. On a fresh data directory:

mkdir -p /tmp/mongo-demo
mongod --dbpath /tmp/mongo-demo --port 27017 --bind_ip 127.0.0.1 --auth &

Now create the admin user using mongosh (before auth is fully required — but our instance is running with --auth, so we need to connect as localhost exception):

mongosh --port 27017 --authenticationDatabase admin -u admin -p secret --eval "db.createUser({user:'admin', pwd:'secret', roles:['root']})"

If you get an error like MongoServerError: Authentication failed., make sure the user exists — the --auth flag means no anonymous access.

Step 2: Connect with a full URI

Now open a new terminal and connect using the URI with credentials:

mongosh "mongodb://admin:secret@localhost:27017/mydb?authSource=admin"

You should see output similar to:

Current Mongosh Log ID: 6478f2d9c4a1b2c3d4e5f6a7
Connecting to:      mongodb://admin:secret@localhost:27017/mydb?authSource=admin
Using MongoDB:      7.0.2
Using Mongosh:      2.1.0

For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/

Note the using MongoDB: 7.0.2 line — that confirms which server version you're talking to.

Step 3: Verify the connection and run a query

Inside the shell, check that you're connected and db is pointing to mydb:

db

Output: mydb

Now insert and read a document:

db.users.insertOne({ name: "Ada", role: "admin" });
db.users.find().pretty();

Output:

{ _id: ObjectId('...'), name: 'Ada', role: 'admin' }

To exit the shell, type:

exit

Step 4: Handle authentication failures gracefully

If you mistype the password, you'll see:

MongoServerError: bad auth Authentication failed.

The connection was made at TCP level, but MongoDB rejected your credentials. Double-check the username, password, and authSource.

Step 5: Use environment variables (optional)

For scripts and CI, avoid hardcoding credentials. Put them in environment variables:

export MONGODB_URI="mongodb+srv://admin:secret@cluster0.mongodb.net/mydb"
mongosh "$MONGODB_URI"

This keeps secrets out of your history and makes commands portable.

Compare options / when to choose what

You have several ways to connect. The table below summarizes when each is the best choice.

Method Use case Example
Defaults (no args) Local development, no auth, lazy Friday mongosh
Full URI Everything else — remote, auth, options mongosh "mongodb://user:pass@host/db?authSource=admin"
Flags Scripts where readability matters mongosh --host x --port y --username u
mongodb+srv URI Atlas / DNS-based cluster lists mongosh "mongodb+srv://cluster.mongodb.net/db"
--eval One-off commands in automation mongosh --eval "db.runCommand({ping:1})"

When to choose what:

  • Prefer defaults for local experimentation — it's fastest.
  • Use a full URI for any configuration beyond the default: authentication, TLS, multiple hosts, or custom app names.
  • Reach for flags when you're building a command dynamically and want to avoid URI escaping headaches.
  • Choose mongodb+srv for Atlas deployments or any cluster where hosts can change — it's the modern standard.

Troubleshooting & edge cases

"Could not connect" / connection refused

The most common issue. Verify the server is actually running:

mongod --version   # should show server version if installed
ps aux | grep mongod

Also check the port — if you started mongod on port 27018, you must specify it.

Bad auth — credentials rejected

The connection succeeds but auth fails. Check:

  • The authentication database (authSource) — if your user was created in admin, you must specify ?authSource=admin, otherwise mongosh defaults to the database in the path.
  • URL encoding of special characters (@, :, /) in password.
  • Whether the user exists on that database — a user created in test won't authenticate against admin unless it has a role in admin.

mongodb+srv fails to resolve

If you get Could not find host matching errors, your DNS SRV records aren't set up, or you're using an incompatible port. Remember, mongodb+srv requires port 27017 (or the default), and it doesn't work with custom ports.

Timeout when connecting to a remote host

If the server is behind a firewall, your connection may hang. Check:

nc -zv yourhost 27017

If the port is open but commands are slow, consider using --quiet or --norc to avoid loading your startup script.

mongosh command not found

Older MongoDB versions come with the mongo shell, not mongosh. Install the latest shell from MongoDB's downloads page, or check that your PATH includes the MongoDB bin directory.

What you learned & what's next

In this lesson, you learned how to connect to MongoDB with mongosh: from the frictionless default connection to explicit URI strings with authentication and options. You now understand the anatomy of a connection string, how authSource affects authentication, and how to troubleshoot the most common connection failures. You also saw how to apply these skills in a practical scenario — you connected to a secure local instance, ran a query, and verified your work.

The next step in your MongoDB journey is to master CRUD operations — inserting, reading, updating, and deleting documents with the mongosh commands you're now able to run reliably. With a solid connection, every subsequent lesson becomes a smooth sandbox experience. So open your terminal, connect, and get ready to manipulate documents with confidence.

Practice recap

Launch a local MongoDB instance with --auth, create an admin user, then connect using the full URI. Test your understanding by running a db.runCommand({ping:1}) and inserting a document. Experiment with --eval to see how you'd use this in a script.

Common mistakes

  • Forgetting the authSource parameter when the user was created in admin, leading to Authentication failed even with correct credentials.
  • Hardcoding credentials in shell history — use environment variables or a config file to avoid leaking secrets.
  • Using mongosh with the wrong port and assuming the default 27017 — always verify by checking mongod startup output.
  • Using mongodb+srv with a custom port, which is not allowed and causes a NonResilientMode error.

Variations

  1. Using mongosh with --host and --port flags instead of a connection string for better readability in scripts.
  2. Connecting via a MongoDB GUI like Compass, which uses the same URI but offers a visual interface.
  3. Using environment variables or shell aliases to store connection strings and avoid repetitive typing.

Real-world use cases

  • Connecting to a MongoDB Atlas cluster from a local development machine using mongodb+srv with credentials.
  • Running one-off admin commands in production using mongosh --eval 'db.runCommand({ping:1})' to verify health.
  • Automating database migrations in CI/CD pipelines by connecting via a script that sources credentials from environment variables.

Key takeaways

  • mongosh defaults to mongodb://localhost:27017, which works for local unauthenticated instances.
  • The connection string URI includes protocol, credentials, host:port, database, and options — master each part.
  • Authentication requires the correct authSource — usually admin — to verify users created there.
  • For Atlas, use mongodb+srv URIs to let DNS resolve hosts automatically.
  • Debug connection issues systematically: check server status, port, credentials, and TLS settings.
  • The --eval flag is invaluable for scripting and automation, allowing direct command execution.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.