As a beginner and newbie to coding, mongo happens to be the first database service I am exploring and the learning journey has been great by far. In order to learn any new tool, framework or service - it is crucial their documentation is clear enough so you can find your way through it. While mongo team does a great job at it, I had to comb through a few documents to find "how I can connect to the mongoDB cluster without leaving my terminal". To make this easier for anyone who is a lazy ass like myself, here are the steps I followed:
Pre-requisites:
- Install/Update atlas-cli and mongosh. If you haven't already, please refer: https://www.mongodb.com/docs/atlas/cli/stable/install-atlas-cli/
- You already have a mongoDB cluster created
- Your ip is whitelisted to access the cluster
Step 1: Creating a profile
atlas config init
- This initiates the profile creation process. All values are optional. If you do not enter the public/private keys or profile name - they keys are auto-generated and profile is set to default.
- I would suggest add the profile name to a preferred short username. The reason being, it can be used as a flag for other cli commands.
- Most importantly, store the details in a secure place especially the dbuser and dbpassword. You'll be frequently needing this information.
- At any point, you can run a spotlight search for finding the config.toml file. This is where your profile related details are stored.
Step 2: Use atlas to authenticate your profile
atlas auth login
- Once your profile is created, you can use the stored credentials to access your mongoDB cluster at any given point.
- The general syntax is
atlas <command> --profile --profileName
- When you run this command, a browser window opens up to asking for a one-time activation code.
- I know, I know. This is the only time you've to leave your terminal.
- Paste the authentication code from your terminal into the browser and you're all set.
Step 3: Retrieve your SRV connection string
atlas clusters connectionStrings describe <clusterName>
- this command returns a standard connection string which will look something like mongodb+srv://clusterName.mongodb.net
- Copy this URL to the clipboard
Step 4 & the final one: Run mongosh
mongosh <connectionString> --username <dbUser>
- To break it down: mongosh - this is for your mongoDB shell.
- is the string you were able to fetch during Step 3
- dbUser is the username you must have saved during step 1 and it needs to be added with the flag --username
- Once you run it, the terminal prompts for a password. This is the database password from Step 1. Enter and TADA!
I am confident there are better and shorter ways to connect to your cluster. If I come across any such solution, I'll definitely share it with everyone. In case you know it already, I am all ears!
Top comments (2)
well explained
hey, thanks.