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
How to List all Users in the Mongo Shell
In MongoDB, user management is an essential aspect of database administration, allowing administrators to control access and permissions for different users. The Mongo Shell provides a powerful interface to interact with MongoDB including managing users. In this article, we'll explore how to list al
3 min read
How to use MongoDB atlas to save data ?
As modern applications require a database for storing data, MongoDB is a great choice. MongoDB Atlas is the global cloud database service for modern applications. We can use it for storing our application data on its server. Follows these steps for how to use MongoDB Atlas for saving data:Step 1: Vi
3 min read
How to Connect to MongoDB Atlas Using Shell?
MongoDB is a highly scalable NoSQL database, renowned for its ability to manage vast amounts of complex and unstructured data. Unlike traditional databases that use a tabular format, MongoDB employs a document-oriented approach, storing data in a flexible, JSON-like format. This makes MongoDB highly
5 min read
How to Secure the MongoDB Database
In todayâs digital era, securing databases is more critical than ever, especially for organizations storing sensitive user and business data. MongoDB, a widely used NoSQL database, requires robust security measures to prevent unauthorized access, data breaches, and cyber threats. By default, MongoDB
11 min read
How to Use Go With MongoDB?
MongoDB is an open-source NoSQL database. It is a document-oriented database that uses a JSON-like structure called BSON to store documents like key-value pairs. MongoDB provides the concept of collection to group documents. In this article, we will learn about How to Use Go With MongoDB by understa
15+ min read
How to use MongoDB Connection String
MongoDB connection strings are essential for establishing connections between applications and MongoDB databases. These strings contain crucial information such as server addresses, authentication credentials and optional parameters, enabling seamless communication. Understanding the structure and c
6 min read
How to Use MongoDB and Mongoose with Node.js ?
MongoDB is a popular NoSQL database that offers flexibility and scalability, making it an excellent choice for modern applications. Mongoose, a powerful ODM (Object Data Modeling) library, simplifies the interaction between MongoDB and Node.js by providing a schema-based solution for data validation
6 min read
MongoDB Shell
MongoDB Shell is a powerful, interactive command-line interface that enables developers and database administrators to perform operations and manage their MongoDB databases using JavaScript syntax. Whether you're a beginner just starting with MongoDB or an experienced user, MongoDB Shell offers a co
5 min read
How to List All Collections in the MongoDB Shell?
Managing collections is a fundamental task in MongoDB database administration. Knowing how to list all collections in the MongoDB shell is essential for understanding your database structure and managing your data effectively. In this article, we'll explore how to list all collections in the MongoDB
3 min read
How to Use MongoDB in Eclipse?
Eclipse is an IDE (integrated development environment) used in computer programming. Eclipse is an IDE in which we can use any type of programming language for which plugins are available. It contains a base workspace and an extensible plug-in system for customizing the environment. Eclipse is free
5 min read