Lesson 1: Installing and Connecting to the MongoDB Shell / Learn
Code Summary: Installing and Connecting to the MongoDB Shell
The following code demonstrates how to install and use mongosh in a Linux environment.
- Update
aptand installgnupg. Then add the MongoDB public GPG key to the system. - Create a list file for MongoDB.
- Update
aptand installmongosh. - Check that
mongoshis installed. - Exit
mongosh.
apt update
apt install <code>gnupg</code>
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu
focal/mongodb-org/6.0 multiverse" | sudo tee
/etc/apt/sources.list.d/mongodb-org-6.0.list
apt update
apt install -y mongodb-mongosh
mongosh --version
exit
Connect to Your Atlas Cluster by Using mongosh
The following code demonstrates how to connect to your MongoDB Atlas cluster by using mongosh.
- Run the
mongoshcommand followed by your connection string. - After connecting to the Atlas cluster, run
db.hello(), which provides some information about the role of themongodinstance you are connected to. - Finally, run the
exitcommand insidemongoshto go back to the terminal.
mongosh "mongodb+srv://<username>:<password>@<cluster_name>.example.mongodb.net"
Alternatively, you can log in by providing the username and password as a command line argument with -u and -p.
mongosh -u exampleuser -p examplepass "mongodb+srv://myatlasclusteredu.example.mongodb.net"
db.hello()
exit