Skip to main content

MongoDB Configuration

Connect to MongoDB for document storage, flexible schemas, and NoSQL data management.

Connection Parameters

Required Fields

  • Host: mongodb.example.com
  • Port: 27017 (default)
  • Database: Database name

Optional Fields

  • Username: Optional (for authenticated connections)
  • Password: Optional
  • Connection Options: Query parameters (e.g., authSource=admin&replicaSet=rs0)
  • Use SSL/TLS: Enable for encrypted connections

Configuration Example

When creating a MongoDB data source, provide the following information:

FieldExample ValueNotes
Nameprod-mongodbUnique identifier
LabelProduction MongoDBDisplay name
Hostmongodb.example.comDatabase hostname
Port27017Default MongoDB port
DatabasemyappDatabase name
Usernameapp_userOptional for auth
Password••••••••Optional, encrypted
Connection OptionsauthSource=adminOptional query params
Use SSL/TLS✓ EnabledRecommended

Connection String Examples

Simple Connection (No Authentication)

mongodb://localhost:27017/myapp

Authenticated Connection

mongodb://app_user:password@mongodb.example.com:27017/myapp

With Connection Options

mongodb://app_user:password@mongodb.example.com:27017/myapp?authSource=admin&replicaSet=rs0

MongoDB Atlas (Cloud)

mongodb+srv://user:password@cluster0.mongodb.net/myapp?retryWrites=true&w=majority

Usage in Applications

Python Example

import os, json
from pymongo import MongoClient

# Parse STRONGLY_SERVICES environment variable
services = json.loads(os.getenv('STRONGLY_SERVICES', '{}'))
datasources = services.get('datasources', {})

# Get MongoDB data source
mongo_config = datasources['prod-mongodb']

# Build connection string
creds = mongo_config['credentials']
if creds.get('username') and creds.get('password'):
url = f"mongodb://{creds['username']}:{creds['password']}@{creds['host']}:{creds['port']}/{creds['database']}"
else:
url = f"mongodb://{creds['host']}:{creds['port']}/{creds['database']}"

# Add connection options if provided
if creds.get('options'):
url += f"?{creds['options']}"

# Connect
client = MongoClient(url, ssl=creds.get('ssl', False))
db = client[creds['database']]

# Query
users = db.users.find({'active': True})

Node.js Example

const { MongoClient } = require('mongodb');

// Parse STRONGLY_SERVICES environment variable
const services = JSON.parse(process.env.STRONGLY_SERVICES || '{}');
const datasources = services.datasources || {};

// Get MongoDB data source
const mongoConfig = datasources['prod-mongodb'];
const creds = mongoConfig.credentials;

// Build connection string
let url;
if (creds.username && creds.password) {
url = `mongodb://${creds.username}:${creds.password}@${creds.host}:${creds.port}/${creds.database}`;
} else {
url = `mongodb://${creds.host}:${creds.port}/${creds.database}`;
}

// Add connection options if provided
if (creds.options) {
url += `?${creds.options}`;
}

// Connect
const client = new MongoClient(url, {
ssl: creds.ssl || false
});

await client.connect();
const db = client.db(creds.database);

// Query
const users = await db.collection('users').find({ active: true }).toArray();

Go Example

package main

import (
"context"
"encoding/json"
"fmt"
"os"

"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
)

func main() {
// Parse STRONGLY_SERVICES environment variable
var services map[string]interface{}
json.Unmarshal([]byte(os.Getenv("STRONGLY_SERVICES")), &services)

datasources := services["datasources"].(map[string]interface{})
mongoConfig := datasources["prod-mongodb"].(map[string]interface{})
creds := mongoConfig["credentials"].(map[string]interface{})

// Build connection string
uri := fmt.Sprintf("mongodb://%s:%s@%s:%v/%s",
creds["username"].(string),
creds["password"].(string),
creds["host"].(string),
creds["port"],
creds["database"].(string))

// Connect
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())

// Query
collection := client.Database(creds["database"].(string)).Collection("users")
cursor, err := collection.Find(context.TODO(), bson.M{"active": true})
if err != nil {
panic(err)
}

var users []bson.M
cursor.All(context.TODO(), &users)
}

Connection Options

Common MongoDB connection options you can add to the Connection Options field:

OptionDescriptionExample
authSourceAuthentication databaseauthSource=admin
replicaSetReplica set namereplicaSet=rs0
retryWritesRetry write operationsretryWrites=true
wWrite concernw=majority
readPreferenceRead preference modereadPreference=secondary
maxPoolSizeConnection pool sizemaxPoolSize=50
tlsEnable TLStls=true

Common Issues

Authentication Failed

  • Verify username and password are correct
  • Check the authentication database (use authSource option)
  • Ensure user exists: db.getUsers() in mongo shell
  • Create user if needed:
use admin
db.createUser({
user: "app_user",
pwd: "password",
roles: [{ role: "readWrite", db: "myapp" }]
})

Connection Refused

  • Verify the host and port are correct
  • Check firewall rules allow connections
  • Ensure MongoDB is listening on the correct interface (check bindIp in mongod.conf)
  • For MongoDB Atlas, whitelist the platform's IP addresses

Database Not Found

  • MongoDB creates databases automatically on first write
  • Ensure your application has write permissions
  • Check if the database exists: show dbs in mongo shell

SSL/TLS Errors

  • Ensure SSL/TLS is enabled on the MongoDB server
  • Verify certificate validity
  • For self-signed certificates, you may need to disable certificate verification (not recommended for production)

Best Practices

  1. Use Authentication: Always enable authentication for production databases
  2. Enable SSL/TLS: Use SSL/TLS for encrypted connections in production
  3. Least Privilege: Create users with minimal required permissions
  4. Connection Pooling: Configure appropriate connection pool sizes
  5. Index Optimization: Create indexes for frequently queried fields
  6. Monitor Performance: Use MongoDB monitoring tools to track query performance
  7. Regular Backups: Implement regular backup strategies

Replica Set Configuration

For high availability, configure a replica set:

Connection Options: replicaSet=rs0&readPreference=secondaryPreferred

This allows:

  • Automatic failover
  • Read distribution across replicas
  • Better availability during maintenance