Managed MongoDB® is currently in public beta. Click here to join the waiting list.
How to connect to a Managed MongoDB® Database Instance
Before you startLink to this anchor
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 clientLink to this anchor
- 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:
With mongoshLink to this anchor
To connect to a public endpoint using the MongoDB® shell:
-
Replace the following variables in the command as described:
mongosh "mongodb+srv://{db-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:
Current Mongosh Log ID: 67ab0096d43bcc1d9ed4336dConnecting to: mongodb+srv://<credentials>@{db-instance-id}.mgdb.{region}.scw.cloud/?appName=mongosh+2.3.8Using MongoDB: 7.0.12Using Mongosh: 2.3.8For mongosh info see: https://docs.mongodb.com/mongodb-shell/rs-{db-instance-id} [primary] test>
To connect to a MongoDB® via a Private Network, use the following command: mongosh "mongodb+srv://{username}:{password}@{instance_id}.{private_network_id}.internal/?tls=true&tlsCAFile={tls_certificate}"
. Make sure you replace the variables indicated within the {}
with their corresponding values.
With PymongoLink to this anchor
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)
To connect to a MongoDB® via a Private Network, use the following connection string: connection_string = f"mongodb+srv://{username}:{password}@{instance_id}.{private_network_id}.internal/?tls=true&tlsCAFile={tls_certificate}"
. Make sure you replace the variables indicated within the {}
with their corresponding values.
With Node.jsLink to this anchor
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 public connection stringconst connectionString = `mongodb+srv://${username}:${password}@${instanceId}.mgdb.${region}.scw.cloud;`// Construct the private connection stringconst connectionString = `mongodb+srv://${username}:${password}@${instanceId}.${privateNetworkId}.internal;`// 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);
With GoLink to this anchor
The following code shows you how to use the mongo
driver to connect using TLS.
package mainimport ("context""crypto/tls""crypto/x509""fmt""io/ioutil""log""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")func main() {// Replace with your MongoDB connection detailsusername := "your_username"password := "your_password"instanceID := "your_instance_id" // your instance_idprivateNetworkID := "your_private_network_id" // Id of your Private Networkregion := "your_region" // the region of your database instance. "fr-par" for Paris.tlsCertificate := "path/to/your_tls_certificate.pem" // path to your TLS certificatedatabaseName = "databaseName"// Read CA certificatecaCert, err := ioutil.ReadFile(tlsCertificate)if err != nil {log.Fatalf("Erreur lors de la lecture du fichier CA: %v", err)}// Create certificate poolcaCertPool := x509.NewCertPool()caCertPool.AppendCertsFromPEM(caCert)tlsConfig := &tls.Config{RootCAs: caCertPool,}// Construct the public connection stringconnectionString := fmt.Sprintf("mongodb+srv://%s:%s@%s.mgdb.%s.scw.cloud", username, password, instanceID, region)// Construct the private connection stringconnectionString := fmt.Sprintf("mongodb+srv://%s:%s@%s.%s.internal", username, password, instanceID, privateNetworkID)// Create a new client and connect to the serverclientOptions := options.Client().ApplyURI(connectionString).SetTLSConfig(tlsConfig)client, err := mongo.Connect(context.TODO(), clientOptions)if err != nil {log.Fatal(err)}// Check the connectionerr = client.Ping(context.TODO(), nil)if err != nil {log.Fatal(err)}fmt.Println("Connected to MongoDB!")// Access a specific collectioncollection := client.Database(databaseName).Collection("your_collection_name")// Example: Find documents in the collectioncursor, err := collection.Find(context.TODO(), map[string]interface{}{})if err != nil {log.Fatal(err)}defer cursor.Close(context.TODO())for cursor.Next(context.TODO()) {var result map[string]interface{}err := cursor.Decode(&result)if err != nil {log.Fatal(err)}fmt.Println(result)}if err := cursor.Err(); err != nil {log.Fatal(err)}// Close the connection once no longer needederr = client.Disconnect(context.TODO())if err != nil {log.Fatal(err)}fmt.Println("Connection to MongoDB closed.")}
With MongooseLink to this anchor
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 privateNetworkId = 'your_private_network_id'; // your private network idconst databaseName = 'databaseName'// Path to your TLS certificate fileconst tlsCertificatePath = path.resolve(__dirname, 'path/to/your_tls_certificate.pem');// Construct the public connection stringconst connectionString = `mongodb+srv://${username}:${password}@${instanceId}.mgdb.${region}.scw.cloud`;// Construct the private connection stringconst connectionString = `mongodb+srv://${username}:${password}@${instanceId}.${privateNetworkId}.internal`;// 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);});