Managed MongoDB® is currently in private beta. Click here to join the waiting list.
How to connect to a MongoDB® Database Instance
Before you start
To complete the actions presented below, you must have:
- A Scaleway account logged into the console
- Owner status or IAM permissions allowing you to perform actions in the intended Organization
- A MongoDB® Database Instance
- Installed either mongosh, or the pymongo distribution for Python, or the Node.js mongodb module or the mongo driver for Go, or Mongoose on your local machine
How to connect via a database client
- Click MongoDB® under Managed Databases on the side menu. A list of your Database Instances displays.
- Click the database name or «See more Icon» > More info to access the Database Instance information page.
- Click «Download Icon» next to the TLS certificate to download it.
- Transfer the file to where you will execute the connection command.
- Return to the console and click Connect in the Connect Database Instance section. A pop-up appears.
- Select a connection mode. The following modes are available:
mongosh
,Python
,Go
,Node.js
andMongoose
. - Replace the variables in the commands with your information.
Find below a detailed description of each connection mode:
mongosh
To connect to a public endpoint using the MongoDB® shell:
-
Replace the following variables in the command as described:
mongosh "mongodb+srv://{instance_id}.mgdb.{region}.scw.cloud" --tlsCAFile {your_certificate.pem} -u {username}{your-certificate.pem}
- the TLS certificate downloaded on step 3.{username}
- the username you defined upon Database Instance creation.{db-instance-id}
- the UUID of your Database Instance.{region}
- the database name you entered upon Database Instance creation. The default is calledrdb
.
-
Run the command.
-
Enter your password when prompted.
If the connection is successful, you should see the following message display on your console, and be able to write queries:
The server generated these startup warnings when bootingPowered by MongoDB® v0.9.0 and PostgreSQL 14.6.
Follow the same procedure to connect to a private endpoint for one node, replacing {privateNetorkName}
with the name of your Private Network:
mongosh "mongodb://{instance_id}-0.{privateNetworkName}" -u {username}
For multiple nodes, replace {db-instance-id}
with the Database Instance UUID of each respective Instance, and {privateNetworkName}
with the names of your Private Network:
"mongodb://{instance_id}-0.{privateNetworkName},{instance_id}-1.{privateNetworkName},{instance_id}-2.{privateNetworkName}" -u {username}
Python
The following code shows you how to use the pymongo
library to connect using TLS.
from pymongo import MongoClient# Replace with your MongoDB® connection detailsusername = "your_username"password = "your_password" # it is best to use environment variables to manage sensitive datainstance_id = "your_instance_id"region = "your_region" #the region of your database instance. "fr-par" if Paristls_certificate = "path/to/your_tls_certificate.pem" # path to your TLS certificate filedatabase_name = "databaseName"# Construct the connection stringconnection_string = f"mongodb+srv://{username}:{password}@{instance_id}.mgdb.{region}.scw.cloud/?tls=true&tlsCAFile={tls_certificate}"# Establish a connectionclient = MongoClient(connection_string)# Access a specific databasedb = client[database_name]# Example: Access a specific collectioncollection = db['your_collection_name']# Now you can interact with the collection, e.g., find documentsdocuments = collection.find({})for doc in documents:print(doc)
Node.js
The following code shows you how to use the mongodb
module to connect using TLS.
const { MongoClient } = require('mongodb');const path = require('path');// Replace with your MongoDB® connection detailsconst username = encodeURIComponent('your_username');const password = encodeURIComponent('your_password');const region = "your_region" // "fr-par" for Paris.const instanceId = 'your_instance_id'; // your instance idconst databaseName = 'databaseName'// Path to your TLS certificate fileconst tlsCertificatePath = path.resolve(__dirname, 'path/to/your_tls_certificate.pem');// Construct the connection stringconst connectionString = `mongodb+srv://${username}:${password}@${instanceId}.mgdb.${region}.scw.cloud`;// Create a new MongoClientconst client = new MongoClient(connectionString, {useNewUrlParser: true,useUnifiedTopology: true,tls: true, // Enable TLS/SSLtlsCAFile: tlsCertificatePath, // Path to the CA certificate file});async function run() {try {// Connect to the MongoDB® serverawait client.connect();console.log('Connected to MongoDB!');// Access the database and collectionconst db = client.db(databaseName);const collection = db.collection('your_collection_name');// Example: Find documents in the collectionconst documents = await collection.find({}).toArray();console.log('Documents:', documents);} catch (err) {console.error(err);} finally {// Close the connectionawait client.close();console.log('Connection to MongoDB® closed.');}}run().catch(console.dir);
Go
The following code shows you how to use the mongo
driver to connect using TLS.
package mainimport ("context""fmt""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {username := "<replace_with_user_name>"password := "<replace_with_password>"host := "<endpoint ip>"port := 1234 // replace with endpoint port numbercaCertPath := "<instance_certificate.crt>"// prepare the uri for the connectionuri := fmt.Sprintf("mongodb://%s:%s@%s:%d/rdb?tls=true&tlsCACert=%s&authMechanism=PLAIN",username,password,host,port,caCertPath,)ctx := context.Background()// connect to the databaseclient, _ := mongo.Connect(ctx, options.Client().ApplyURI(uri))// get the databasedb := client.Database("rdb")// get the collectioncars := db.Collection("cars")// insert a documentcarToInsert := Car{Name: "Supercar", Year: 2020}cars.InsertOne(ctx, carToInsert)// read the documentcarToRead := Car{}cars.FindOne(ctx, map[string]interface{}{"name": "Supercar"}).Decode(&carToRead)// print the documentfmt.Println(carToRead)}type Car struct {Name stringYear int}
Mongoose
The following code shows you how to use the Mongoose
schema to connect using TLS.
const mongoose = require('mongoose');const path = require('path');// Replace with your MongoDB® connection detailsconst username = encodeURIComponent('your_username');const password = encodeURIComponent('your_password');const region = "your_region" // "fr-par" for Paris.const instanceId = 'your_instance_id'; // your instance idconst databaseName = 'databaseName'// Path to your TLS certificate fileconst tlsCertificatePath = path.resolve(__dirname, 'path/to/your_tls_certificate.pem');// Construct the connection stringconst connectionString = `mongodb+srv://${username}:${password}@${instanceId}.mgdb.${region}.scw.cloud`;// Connect to MongoDB® using Mongoosemongoose.connect(connectionString, {useNewUrlParser: true,useUnifiedTopology: true,tls: true, // Enable TLS/SSLtlsCAFile: tlsCertificatePath, // Path to the CA certificate file}).then(() => {console.log('Connected to MongoDB® with Mongoose!');}).catch(err => {console.error('Connection error', err);});// Example schema and modelconst exampleSchema = new mongoose.Schema({name: String,age: Number,});const ExampleModel = mongoose.model('Example', exampleSchema);// Example: Creating a new documentconst exampleDoc = new ExampleModel({ name: 'John Doe', age: 30 });exampleDoc.save().then(doc => {console.log('Document saved:', doc);}).catch(err => {console.error('Error saving document', err);});