How To Use the MongoDB Shell
Last Updated :
24 Jan, 2025
The MongoDB Shell, also known as mongosh
is a powerful command-line interface that allows users to interact with MongoDB databases. It provides a REPL (Read-Eval-Print Loop) environment that facilitates database management, data manipulation, and administrative tasks with ease
In this comprehensive guide, we will walk you through the process of using the MongoDB Shell, from basic commands to advanced functionality, with a full explanation of each feature.
What is the MongoDB Shell?
The MongoDB Shell (mongosh) is a JavaScript interface for interacting with MongoDB databases. It provides a command-line environment where you can execute MongoDB commands to manage your database, perform administrative tasks, and manipulate data. In short, the MongoDB Shell allows you to manage and work with your MongoDB databases directly through a flexible and powerful command-line interface.
Key features of the MongoDB Shell include:
- Interacting with MongoDB databases: Connect to and manage MongoDB instances.
- Running administrative commands: Perform tasks like managing users, roles, and collections.
- Querying and manipulating data: Use MongoDB’s powerful querying capabilities to read, write, and update data.
- Automating tasks: Execute JavaScript code within the shell to automate repetitive tasks or run scripts for bulk operations.
System Requirements for MongoDB Shell
Before you start using the MongoDB Shell, it's important to ensure that your system meets the necessary requirements for installation and operation. So let's ensure your system is ready for installation.
1. Supported Versions:
- MongoDB 4.4+ (64-bit only).
2. Compatible Operating Systems:
- Windows Server 2022
- Windows Server 2019
- Windows 11
- Linux
- macOS
3. Permissions Required:
Ensure you have the appropriate user permissions to run MongoDB services:
- Performance Monitor Users
- Performance Log Users
How to Start MongoDB Using the Shell?
Starting MongoDB using the Shell is straightforward. Below are the steps to start the MongoDB using Shell are as follows:
Step 1: Connecting to MongoDB Server
- Open your terminal (Command Prompt on Windows, or terminal on macOS/Linux).
- Run the following command to start the MongoDB shell:
mongosh
- This connects you to the default MongoDB instance running on localhost (127.0.0.1).
- If you're connecting to a remote MongoDB instance or using authentication, you can specify the URI like this:
mongosh "mongodb://<username>:<password>@<hostname>:<port>/<database>"
Output after 'mongosh' commandStep 2: Executing MongoDB Commands
Like any other command-line interface, we can enter MongoDB commands directly in the shell. Here are some essential ones:
1. Listing Databases
To list all databases on your MongoDB instance, use:
show dbs
displays all databases present locally2. Switching Databases
To switch to a specific database, use the use
command followed by the database name:
use <database_name>
Example:
use admin
3. Creating Collections
To create a collection within the selected database, you can simply insert a document into a collection, and MongoDB will create it automatically. Here's an example:
db.createCollection("myCollection")
Alternatively, you can insert data directly into a non-existing collection, and it will be created:
db.myCollection.insert({ name: "MongoDB", type: "Database" })
4. Querying Data
To query data from a collection, use the find
method:
db.myCollection.find({ name: "MongoDB" })
This will return all documents where the name is "MongoDB".
Advanced MongoDB Shell Commands
Once you're comfortable with the basic commands, you can explore more advanced features.
1. Running JavaScript in the MongoDB Shell
You can execute JavaScript files directly within the MongoDB Shell using the load()
command. This is particularly useful for automating tasks.
load('myScript.js')
2. Creating a New Connection
You can create a new connection to another MongoDB instance using the Mongo()
function:
var conn = new Mongo("mongodb://<hostname>:<port>")
This allows you to manage multiple connections to different databases.
3. Administrative Commands
The MongoDB Shell also provides commands for administrative tasks such as managing users, roles, and profiling:
Managing Users
To list users in the current database, use:
show users
To create a new user, you can use the db.createUser()
function:
db.createUser({
user: "myUser",
pwd: "myPassword",
roles: [ { role: "readWrite", db: "myDatabase" } ]
})
Managing Roles
To see the roles in the current database:
show roles
4. Enabling/Disabling Telemetry
MongoDB Shell provides the option to enable or disable telemetry to collect usage statistics. To enable:
enableTelemetry
To disable:
disableTelemetry
5. Clear the Shell Screen
To clear the screen in the shell, use:
cls
Getting Interactive Help from the MongoDB Shell
- The MongoDB Shell commands provide essential functionality for interacting with MongoDB databases.
- Commands like
use
and show
allow us to switch databases and display information about databases and collections. exit
and quit
are used to exit the shell.
- The
Mongo
and connect
commands are used to create new connections to MongoDB servers. The load
command loads and runs JavaScript files in the shell environment.
- Overall, these commands streamline database management tasks and enhance the MongoDB Shell's usability.
MongoDB shell have in-built help system that we can use to get information on database system’s available commands and their syntax. The help screen can be accessed by using help command.
help
Output:
Shell Help:
use Set current database
show 'show databases'/'show dbs': Print a list of all available databases.
'show collections'/'show tables': Print a list of all collections for current database.
'show profile': Prints system.profile information.
'show users': Print a list of all users for current database.
'show roles': Print a list of all roles for current database.
'show log <type>': log for current connection, if type is not set uses 'global'
'show logs': Print all logs.
exit Quit the MongoDB shell with exit/exit()/.exit
quit Quit the MongoDB shell with quit/quit()
Mongo Create a new connection and return the Mongo object. Usage: new Mongo(URI, options [optional])
connect Create a new connection and return the Database object. Usage: connect(URI, username [optional], password [optional])
it result of the last line evaluated; use to further iterate
version Shell version
load Loads and runs a JavaScript file into the current shell environment
enableTelemetry Enables collection of anonymous usage data to improve the mongosh CLI
disableTelemetry Disables collection of anonymous usage data to improve the mongosh CLI
passwordPrompt Prompts the user for a password
sleep Sleep for the specified number of milliseconds
print Prints the contents of an object to the output
printjson Alias for print()
convertShardKeyToHashed Returns the hashed value for the input using the same hashing function as a hashed index.
cls Clears the screen like console.clear()
isInteractive Returns whether the shell will enter or has entered interactive mode
This will display a list of available commands. To get help on a specific command, you can use:
help <command>
Example:
help show
List of Commonly Used MongoDB Shell Commands
Here is a quick reference for some commonly used MongoDB Shell commands:
- use: Switch between databases.
- show dbs: List all databases.
- show collections: List all collections in the current database.
- show users: List all users in the current database.
- show roles: List all roles in the current database.
- exit/quit: Exit the MongoDB shell.
- load(): Run a JavaScript file in the shell.
- db.<collection>.find(): Query data from a collection.
- db.createCollection(): Create a new collection.
- db.createUser(): Create a new user.
Conclusion
The MongoDB Shell is an essential tool for database administrators and developers working with MongoDB. By mastering the basic and advanced commands covered in this guide, users can perform tasks ranging from simple data manipulation to complex administrative operations.
The interactive help system within the shell makes it even easier to navigate and explore MongoDB's vast capabilities. With this knowledge, you’ll be able to interact with your MongoDB instance efficiently, whether you’re just getting started or managing large-scale databases.
Similar Reads
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read