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:
| Field | Example Value | Notes |
|---|---|---|
| Name | prod-mongodb | Unique identifier |
| Label | Production MongoDB | Display name |
| Host | mongodb.example.com | Database hostname |
| Port | 27017 | Default MongoDB port |
| Database | myapp | Database name |
| Username | app_user | Optional for auth |
| Password | •••••••• | Optional, encrypted |
| Connection Options | authSource=admin | Optional query params |
| Use SSL/TLS | ✓ Enabled | Recommended |
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:
| Option | Description | Example |
|---|---|---|
authSource | Authentication database | authSource=admin |
replicaSet | Replica set name | replicaSet=rs0 |
retryWrites | Retry write operations | retryWrites=true |
w | Write concern | w=majority |
readPreference | Read preference mode | readPreference=secondary |
maxPoolSize | Connection pool size | maxPoolSize=50 |
tls | Enable TLS | tls=true |
Common Issues
Authentication Failed
- Verify username and password are correct
- Check the authentication database (use
authSourceoption) - 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
bindIpin 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 dbsin 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
- Use Authentication: Always enable authentication for production databases
- Enable SSL/TLS: Use SSL/TLS for encrypted connections in production
- Least Privilege: Create users with minimal required permissions
- Connection Pooling: Configure appropriate connection pool sizes
- Index Optimization: Create indexes for frequently queried fields
- Monitor Performance: Use MongoDB monitoring tools to track query performance
- 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