Mongo Shell

Mongo Shell is the command-line interface used to connect to MongoDB, run queries, inspect databases, and perform administrative tasks. In current MongoDB versions, the shell command is mongosh. The older mongo shell is kept in this tutorial as a legacy reference because many older examples and installations still mention it.

The current MongoDB Shell, mongosh, is a JavaScript and Node.js based REPL for working with MongoDB deployments locally, on another server, or in MongoDB Atlas. For current installation packages and platform-specific instructions, refer to the official MongoDB Shell documentation and MongoDB Shell download page.

Before opening Mongo Shell, make sure mongod is running

Prior to connecting to MongoDB, ensure that the MongoDB server process is running. If it is not, start MongoDB.

On modern Ubuntu systems, start the MongoDB service with systemctl and verify the service status.

</>
Copy
sudo systemctl start mongod
sudo systemctl status mongod

If the service is enabled, MongoDB will start automatically after reboot.

</>
Copy
sudo systemctl enable mongod

To start MongoDB, run the following command in a terminal.

Windows

</>
Copy
 C:\> "C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe"

Ubuntu

sudo service mongod start

Install or check MongoDB Shell mongosh on your computer

If MongoDB was installed from current official packages, mongosh may already be available. Check it from the terminal first.

</>
Copy
mongosh --version

If the command is not found, install MongoDB Shell separately using the package for your operating system from the official MongoDB Shell download page. On Linux, install the package that matches your distribution and CPU architecture. On Windows, install the MSI package and open a new command prompt after installation so that the updated PATH is available.

Start Mongo Shell with mongosh for a local MongoDB server

Once MongoDB is running, open a new terminal and run mongosh. Without a connection string, mongosh tries to connect to MongoDB on localhost using the default port 27017.

</>
Copy
mongosh

To confirm that the shell is connected to the server, run a simple ping command inside mongosh.

</>
Copy
db.runCommand({ ping: 1 })
{ ok: 1 }

To see the current database selected by the shell, run:

</>
Copy
db
test

test is the default database shown when you connect without selecting another database.

Connect mongosh to a MongoDB host, port, or connection string

If MongoDB is running on a different host or a non-default port, provide the host and port explicitly. This is common when you have multiple MongoDB instances or when the server is running on another machine in your network.

</>
Copy
mongosh --host <host> --port <port_number>

Example:

</>
Copy
mongosh --host 192.168.0.104 --port 28019

You can also use a MongoDB connection string. This format is often easier to copy from deployment settings and works for local, remote, and Atlas connections.

</>
Copy
mongosh "mongodb://<host>:<port>/<database>"

For a local server and a database named school, the command can be written as:

</>
Copy
mongosh "mongodb://localhost:27017/school"

For an authenticated MongoDB deployment, provide the username and authentication database. You can let the shell prompt for the password instead of typing it directly in the command history.

</>
Copy
mongosh "mongodb://<host>:<port>/<database>" -u <username> -p --authenticationDatabase admin

If you connect to MongoDB Atlas, copy the mongodb+srv:// connection string from the Atlas Connect dialog, replace the placeholders, and run it with mongosh.

</>
Copy
mongosh "mongodb+srv://<username>@<cluster-url>/<database>"

Use Mongo Shell commands to inspect databases and collections

After connecting, these mongosh commands help you inspect the server, switch databases, and view collections. Commands such as show dbs and show collections are shell helpers, while commands such as db.stats() and db.version() are JavaScript method calls in the shell context.

Mongo Shell commandWhat it does
helpShows shell help.
show dbsLists databases visible to the current user.
use schoolSwitches the current database to school.
show collectionsLists collections in the selected database.
dbPrints the current database name.
db.stats()Shows statistics for the current database.
db.version()Shows the connected MongoDB server version.
exitCloses the shell session.

Example shell session:

</>
Copy
show dbs
use school
show collections
db.stats()
exit

Run basic CRUD commands in MongoDB Shell mongosh

The shell is also useful for quick data checks while learning MongoDB. The following example switches to a database, inserts one document, reads it back, updates it, and deletes it.

</>
Copy
use school

db.students.insertOne({ name: "Anu", class: 8, subject: "Math" })

db.students.find({ name: "Anu" })

db.students.updateOne(
  { name: "Anu" },
  { $set: { subject: "Science" } }
)

db.students.deleteOne({ name: "Anu" })

For production data, avoid running write or delete commands casually from the shell. Confirm the database name with db and test filters with find() before using updateOne(), updateMany(), deleteOne(), or deleteMany().

Run a JavaScript file from MongoDB Shell

mongosh can run a JavaScript file from the command line. This is useful for setup scripts, development checks, or repeatable administrative commands.

</>
Copy
// check-students.js
use("school");
printjson(db.students.findOne());
</>
Copy
mongosh "mongodb://localhost:27017/school" --file check-students.js

When a script needs credentials, prefer secure environment variables, a protected connection string, or an appropriate secrets workflow instead of saving plain-text passwords in script files.

Troubleshoot common Mongo Shell connection errors

Most shell connection errors are caused by the MongoDB service being stopped, the wrong port, missing authentication details, or network rules blocking the connection.

Mongo Shell problemLikely causeWhat to check
ECONNREFUSED or connect failedmongod is not running or the port is wrong.Run sudo systemctl status mongod and confirm the port in /etc/mongod.conf.
mongosh: command not foundMongoDB Shell is not installed or not in PATH.Install mongosh from the official download page and open a new terminal.
Authentication failedWrong username, password, or authentication database.Check the user, password prompt, and --authenticationDatabase value.
Remote connection times outFirewall, bind IP, or network access rule blocks the connection.Check firewall rules, server bind address, and whether the client IP is allowed.
Atlas connection failsAtlas user, password, IP access list, or URI is incorrect.Use the Atlas Connect dialog and verify the database user and network access list.

Mongo Shell QA checklist for this tutorial

  • Use mongosh for current MongoDB versions and keep mongo only as a legacy command.
  • Confirm the MongoDB server process mongod is running before starting the shell.
  • Mention that the default local connection is localhost:27017.
  • Include connection examples for local, host-and-port, authenticated, and Atlas-style URI usage.
  • Show safe beginner commands such as db, show dbs, use, and show collections.
  • Warn readers to verify the active database and query filter before running update or delete commands.

Legacy Start Mongo Shell command with mongo

The section below shows the older mongo shell commands used with MongoDB 3.4 and similar legacy installations. On current installations, use mongosh instead.

Once you are sure that MongoDB is running,

Windows

Open another Command Window and run the following command.

</>
Copy
 C:\> "C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe"

Ubuntu

Open another Terminal and run the following command to start mongo shell.

mongo
arjun@arjun-VPCEH26EN:~$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	http://docs.mongodb.org/
Questions? Try the support group
	http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2017-10-15T12:35:20.897+0530 I STORAGE  [initandlisten] 
2017-10-15T12:35:20.897+0530 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-10-15T12:35:20.897+0530 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-10-15T12:35:22.336+0530 I CONTROL  [initandlisten] 
2017-10-15T12:35:22.336+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-10-15T12:35:22.337+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-10-15T12:35:22.337+0530 I CONTROL  [initandlisten] 
2017-10-15T12:35:22.337+0530 I CONTROL  [initandlisten] 
2017-10-15T12:35:22.337+0530 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-10-15T12:35:22.337+0530 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-10-15T12:35:22.337+0530 I CONTROL  [initandlisten] 
2017-10-15T12:35:22.337+0530 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2017-10-15T12:35:22.337+0530 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-10-15T12:35:22.337+0530 I CONTROL  [initandlisten] 
> 

If the server is not running, you may get connect failed message as below :

arjun@arjun-VPCEH26EN:~$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
2017-10-15T12:25:19.606+0530 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2017-10-15T12:25:19.667+0530 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:237:13
@(connect):1:6
exception: connect failed

When no parameters are provided with mongo command, the default functionality is that, the mongo shell tries to make a connection to the MongoDB server running at localhost on port 27017.

But if you like to connect to MongoDB server that is running on a different machine connected to your network, you may make use of the options of mongo shell as shown below

mongo --host <host> --port <port_number>

An example is provided below

mongo --host 192.168.0.104 --port 28019

Now we shall run a simple query db to know the database the shell is pointing to.

> db
test

test is a default database.

Start Mongo Shell for a specified MongoDB instance among multiple instances

If you come across the scenario that there are multiple MongoDB instances running in a same machine, but on the different ports of-course, then to connect to a particular MongoDB instance differentiated by the port it is running on, run the following command :

mongo --port <port_number>

Following is an example demonstrating to open a Mongo Shell connected to a MongoDB instance running at 27018.

mongo --port 27018

Legacy Mongo Shell commands used in older mongo examples

Following are a useful list of Mongo Shell Commands :

  • help – show help
  • help admin – administrative help
  • help connect – connecting to a db help
  • help keys – key shortcuts
  • help misc – misc things to know
  • help mr – mapreduce
  • show dbs – show database names
  • show collections – show collections in current database
  • show users – show users in current database
  • show profile – show most recent system.profile entries with time >= 1ms
  • show logs – show the accessible logger names
  • show log [name] – prints out the last segment of log in memory, ‘global’ is default
  • use <db_name> – set current database
  • it – result of the last line evaluated; use to further iterate
  • exit – quit the mongo shell

Mongo Shell mongosh FAQs

What is Mongo Shell?

Mongo Shell is the command-line interface for interacting with MongoDB. The current shell is mongosh, which lets you connect to MongoDB, run queries, inspect databases, execute JavaScript, and perform administrative tasks.

What is the difference between mongo and mongosh?

mongo is the legacy MongoDB shell used by older MongoDB versions. mongosh is the current MongoDB Shell and should be used for new installations and current documentation.

How do I start MongoDB Shell from the terminal?

Start the MongoDB server first, then run mongosh in a new terminal. By default, it connects to localhost:27017.

How do I connect mongosh to a remote MongoDB server?

Use mongosh --host <host> --port <port_number> or pass a full connection string such as mongosh "mongodb://host:27017/database". For authenticated deployments, include the username and authentication database and allow the shell to prompt for the password.

Why does Mongo Shell show connection refused?

Connection refused usually means the MongoDB server is not running, the shell is connecting to the wrong port, or the server is not listening on the requested network address. Check the mongod service status, port, bind IP, and firewall settings.

Mongo Shell tutorial recap

In this MongoDB Tutorial, we learnt what Mongo Shell is, how to start the current mongosh shell, how to connect to local and remote MongoDB deployments, how to run basic database commands, and how older mongo shell commands relate to legacy MongoDB installations.