Database Usage
We deployed a mongo database on the cloud. This database is accessible with string connection.
Prerequisite
Make sure you have locally installed:
There is multiple ways to connect to the mongo database using a connection string.
The string looks like this “mongodb://USER:PWD@HOST:PORT”. Let’s find the appropriate values for USER, PWD, HOST and PORT in this sheet.
1. From the command line interface:
$ mongosh "mongodb://USER:PWD@HOST:PORT"
Current Mongosh Log ID: <CONNECTION_ID>
Connecting to: mongodb://<credentials>@HOST:27017/?directConnection=true&appName=mongosh+1.3.1
Using MongoDB: 5.0.7
Using Mongosh: 1.3.1
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
Warning: Found ~/.mongorc.js, but not ~/.mongoshrc.js. ~/.mongorc.js will not be loaded.
You may want to copy or rename ~/.mongorc.js to ~/.mongoshrc.js.
test>
Then you can write mongo commands. Let’s start with this tutorial.
2. From Python with pymongo
import os
import pymongo
#setting variables
USER=os.getenv("MONGO_USER")
PWD=os.getenv("MONGO_PWD")
HOST=os.getenv("MONGO_HOST")
PORT=os.getenv("MONGO_PORT")
#creating string connexion
conn=f"mongodb://{USER}:{PWD}@{HOST}:{PORT}"
# connexion to database.
client = pymongo.MongoClient(conn)
To start using mongo with python, let’s check this tutorial.
3. From Scala using a mongodb driver
import com.mongodb.MongoClientSettings
import com.mongodb.MongoException
import com.mongodb.client.MongoClient
import com.mongodb.client.MongoClients
import com.mongodb.client.MongoDatabase
val uri = "mongodb://USER:PWD@HOST:PORT/"
val mongoClient = MongoClients.create(uri)
val database = mongoClient.getDatabase(mongoDatabase)
To start using mongo with scala/java, let’s check tutorial.