Mongo shell is an interactive command window for MongoDB. You can use the mongo shell to perform various CRUD operations on MongoDB, such as querying, updating, and deleting data. The mongo shell comes bundled with MongoDB installation and does not require a separate installation.
Note: In the following chapters, the main focus will be on using mongo shell commands and APIs to introduce various MongoDB operations. If you are using programming languages or the MongoDB Compass for visual operations, their syntax is similar to the mongo shell. Therefore, mastering the syntax of the mongo shell will also help you understand the usage of other tools.
Starting mongo Shell and Connecting to MongoDB
Connecting to the local MongoDB Server
Simply enter the mongo
command to enter the Mongo Shell.
mongo
This will connect to the MongoDB Server using the default address.
Note: If the mongo
command is not found, it means that the MongoDB bin directory was not added to the PATH environment variable during installation. You can refer to the installation chapter for specific steps.
If successful, the following information will be displayed:
MongoDB shell version v4.4.5
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b11bfc3e-e70c-42b1-9bfc-5d9218f2d232") }
MongoDB server version: 4.4.5
>
You can now enter operation commands in the interactive window.
Accessing the mongo shell within a Docker container
If you are using a Docker container named mongo
for MongoDB installation, you can directly access the mongo shell using the following command:
docker exec -it mongo mongo
Connecting to a remote MongoDB Server
mongo --username root --password --host mongodb0.examples.com --port 28015
Parameter explanations:
-
--username
: Set the MongoDB account to root -
--password
: It will prompt you to enter the password -
--host
: Specify the MongoDB server address -
--port
: Specify the MongoDB server port
Basic mongo shell commands
Displaying the current database name in use
db
Switching to another database
Syntax:
use database_name
Example:
use tizi365
Examples of mongo shell operations
// Switching database
use myNewDatabase
// Inserting a record
db.myCollection.insertOne( { x: 1 } );
// Querying all data in the inventory collection
db.inventory.find( {} )
// Querying documents in the inventory collection where status = "D"
db.inventory.find( { status: "D" } )
More mongo shell operation commands will be introduced in later chapters.
Exiting the mongo shell
Press