Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 70 ยท Getting started

Installing MongoDB and Using mongosh

Install MongoDB locally, in Docker or on Atlas, connect with mongosh, learn the basic shell commands and read connection strings, with runnable stand-ins.

To follow along with a real database you need two things: a MongoDB server (the mongod process that stores data) and a client to talk to it. The client you will use most is mongosh, the MongoDB Shell, an interactive JavaScript environment where you type commands such as db.products.find(). Later, your own applications will talk to the server through a driver instead (Using MongoDB from Node.js).

You have three practical ways to get a server: install it on your computer, run it in a Docker container, or create a free cluster on MongoDB Atlas, the hosted service. All three give you the same database. You do not need any of them to follow this tutorial, because every TryIt runs on a stand-in engine in your browser, but trying the real commands is the best way to learn.

Read-only commands. The install and shell commands in this lesson are real, but they run on your machine, not on this site. Installer details change between releases, so use the official installation page for your platform for exact, current steps. The TryIts here are small JavaScript stand-ins that explain how connection strings and shell commands work.

Three ways to get a server

Local install mongod runs as a service on your computer.
Docker One command, easy to throw away.
Atlas A hosted cluster with a free tier.

Pick one. The commands you type afterwards are identical.

1 / 2

Option 1: install locally

MongoDB Community Edition is free. The server and the shell are separate downloads, though most installers offer both.

  • Windows: download the MSI installer from MongoDB's download page and choose to run MongoDB as a service. Optionally install MongoDB Compass, a graphical client, from the same installer.
  • macOS: the usual route is Homebrew, using MongoDB's own tap:
Terminal
brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community
  • Linux: add MongoDB's package repository for your distribution and install the mongodb-org packages with apt, dnf or zypper, then start the mongod service with systemctl.

After installation, mongod listens on port 27017 and by default accepts connections only from the same machine. It stores its data in a data directory (for example /var/lib/mongodb on Linux packages) and, on a fresh install, does not require a login. That is fine for learning on your laptop and not fine for anything reachable from a network. Authentication and Role-Based Access shows how to turn security on.

If mongosh was not installed with the server, install it separately from the MongoDB Shell download page.

Option 2: run it in Docker

If you already use Docker (Installing Docker), a container is the fastest and cleanest route:

Terminal
docker run -d --name mongo -p 27017:27017 -v mongo-data:/data/db mongo:8
docker exec -it mongo mongosh

The first command starts the official mongo image in the background, publishes port 27017, and keeps the data in a named volume called mongo-data so it survives container restarts. The second command opens mongosh inside the container. Remove -v mongo-data:/data/db if you want a disposable database that disappears with the container. See Running Containers for the options used here.

Option 3: MongoDB Atlas free tier

Atlas runs MongoDB for you in the cloud. After you create an account, you can start a free shared cluster (the free tier is limited in storage and is meant for learning and small experiments). The setup has three steps:

  1. Create the cluster and choose a cloud provider and region.
  2. Create a database user with a username and password. This is separate from your Atlas login.
  3. Add your IP address to the network access list, otherwise connections are refused.

Atlas then gives you a connection string to paste into mongosh, Compass or your application. More in MongoDB Atlas Overview.

Connecting with mongosh

Run mongosh with no arguments to connect to a local server on the default port. Pass a connection string to connect anywhere else:

Terminal
mongosh
mongosh "mongodb://localhost:27017"
mongosh "mongodb+srv://appuser:[email protected]/shop"

Never paste a real password into a command that ends up in shared logs or your shell history. Prefer a password prompt (--username appuser makes mongosh ask for the password) or an environment variable.

Once connected you see a prompt such as test>. The word is the current database. These commands are the ones you will use every day:

JavaScript
show dbs                  // list databases that contain data
use shop                  // switch to the "shop" database
db                        // print the current database name
show collections          // list collections in the current database
db.products.insertOne({ name: "Yoga Mat", price: 30 })
db.products.find()
db.products.countDocuments()
db.dropDatabase()         // delete the current database. Careful!
exit                      // leave the shell

mongosh is a JavaScript shell, so loops, variables and functions work. show dbs and use are shell helpers, not JavaScript. Two behaviours surprise beginners: use shop does not create anything until you write a document, and show dbs hides databases that are empty.

A shell helper stand-in

This stand-in shows how those helpers behave. It keeps databases in an object, creates them lazily on the first insert, and hides empty ones from show dbs, like the real shell.

JS How show dbs and use behave

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reading a connection string

A connection string tells a client where the server is, how to log in, and which options to use. The general shape is:

TEXT
mongodb://[user:password@]host1[:port1][,host2[:port2],...]/[database][?options]
  • mongodb:// names hosts directly. A replica set lists several hosts separated by commas (Replica Sets).
  • mongodb+srv:// is used by Atlas. The hostname is looked up in DNS, which returns the actual server list and enables TLS automatically, so the string stays short. A +srv string takes exactly one hostname and no port.
  • The path after the host is the database, which is also where authentication defaults to unless authSource says otherwise.
  • Options come after ?, for example retryWrites=true, w=majority (Read and Write Concerns), replicaSet=rs0, authSource=admin.
  • A password with special characters (@, :, /, %) must be percent-encoded.

The next stand-in splits a connection string into its parts. It is a teaching tool, not a validator: real drivers follow the full specification.

JS Taking a connection string apart

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Troubleshooting first connections

  • Connection refused on localhost: mongod is not running. Start the service or the container, and check that nothing else uses port 27017.
  • Timeout to Atlas: your IP address is not on the network access list.
  • Authentication failed: wrong user or password, or the user was created in a different database than authSource. Atlas database users are not the same as your Atlas account.
  • Command not found: mongosh is a separate program from mongod, so install it if needed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which port does mongod listen on by default?

    27017 is MongoDB's default port. 3306 is MySQL and 5432 is PostgreSQL.
  2. 2. You run use shop in mongosh and then show dbs. The shop database is not listed. Why?

    use only changes the current database name. Nothing exists on the server until you insert a document.
  3. 3. What is special about a mongodb+srv:// connection string?

    The SRV scheme looks up the member list in DNS, so Atlas strings stay short, and it turns TLS on by default.
  4. 4. A fresh local mongod install accepts connections without a password. What should you do before exposing it beyond your own machine?

    A default install is meant for local learning. Anything reachable from a network needs authentication, firewalling and encryption.

Summary

  • mongod is the server and mongosh is the interactive shell. Both default to port 27017 and localhost.
  • Get a server by installing locally, running the mongo image in Docker, or creating a free Atlas cluster.
  • Core shell commands: show dbs, use, db, show collections, then db.<collection>.insertOne() and find().
  • Databases and collections appear only after the first write.
  • A connection string holds the scheme, credentials, hosts, database and options; mongodb+srv:// finds hosts through DNS.
  • A default local install has no authentication. Secure it before exposing it.

Next, meet the engine behind this tutorial's runnable examples in The Practice Engine Used in This Tutorial.