MongoDB Configuration
Connect to MongoDB for document storage, flexible schemas, and NoSQL data management.
Connection Parameters
Required Fields
| Field | Description | Example |
|---|---|---|
| Host | Database hostname | mongodb.example.com |
| Port | MongoDB port (default: 27017) | 27017 |
| Database | Database name | myapp |
Optional Fields
| Field | Description | Example |
|---|---|---|
| Username | For authenticated connections | app_user |
| Password | Authentication password | |
| Connection Options | Query parameters | 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 |
|---|---|---|
| Data source label | prod-mongodb | Kebab-case unique identifier (used as both name and label) |
| Host | mongodb.example.com | Database hostname |
| Port | 27017 | Default MongoDB port |
| Database | myapp | Database name |
| Username | app_user | Optional for auth |
| Password | password | Optional, encrypted at rest |
| Connection Options | authSource=admin | Optional query parameters |
| Use SSL/TLS | Enabled | Recommended for production |
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
Test Connection
When you create or test a MongoDB data source, the platform connects using the MongoDB Node.js driver. If a connectionString is provided in credentials, it is used directly; otherwise one is built from the host, port, username, password, and database fields. The test executes a ping command against the database. The connection uses a 10-second timeout for both server selection and initial connect.
Schema Discovery
MongoDB has full native schema discovery support. Clicking Refresh Metadata returns:
- Collections: All collections in the specified database (returned in the
tablesfield for consistency) - Databases: All non-system databases (excluding
admin,local,config) - Size: Database data size in bytes (via
db.stats()) - Row count: Total object count across the database (via
db.stats())
If authSource and SSL options are provided in the Connection Options field, they are appended to the connection URI during metadata fetching.
Column-Level Metadata
MongoDB supports column-level (field-level) discovery for individual collections. The platform samples up to 100 documents from the collection and infers the schema by examining field names and JavaScript types (including ObjectId, Date, Array). The _id field is marked as the primary key.
Usage in Workflows (STRONGLY_SERVICES)
When a MongoDB data source is attached to a workflow, credentials are injected via STRONGLY_SERVICES with all fields at the top level (not nested under a credentials key). A connectionString is included since MongoDB is a supported connection string type:
{
"datasources": {
"prod_mongodb": {
"type": "mongodb",
"name": "prod-mongodb",
"host": "mongodb.example.com",
"port": 27017,
"database": "myapp",
"username": "app_user",
"password": "actual_password",
"connectionString": "mongodb://app_user:***@mongodb.example.com:27017/myapp"
}
}
}
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 (key is sanitized name: hyphens become underscores)
mongo = datasources['prod_mongodb']
# Build connection string from top-level fields
if mongo.get('username') and mongo.get('password'):
url = f"mongodb://{mongo['username']}:{mongo['password']}@{mongo['host']}:{mongo['port']}/{mongo['database']}"
else:
url = f"mongodb://{mongo['host']}:{mongo['port']}/{mongo['database']}"
# Add connection options if provided
if mongo.get('options'):
url += f"?{mongo['options']}"
# Connect
client = MongoClient(url, ssl=mongo.get('ssl', False))
db = client[mongo['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 (key is sanitized name)
const mongo = datasources['prod_mongodb'];
// Build connection string from top-level fields
let url;
if (mongo.username && mongo.password) {
url = `mongodb://${mongo.username}:${mongo.password}@${mongo.host}:${mongo.port}/${mongo.database}`;
} else {
url = `mongodb://${mongo.host}:${mongo.port}/${mongo.database}`;
}
// Add connection options if provided
if (mongo.options) {
url += `?${mongo.options}`;
}
// Connect
const client = new MongoClient(url, {
ssl: mongo.ssl || false
});
await client.connect();
const db = client.db(mongo.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{})
// Access top-level fields directly (no "credentials" nesting)
mongoDS := datasources["prod_mongodb"].(map[string]interface{})
// Build connection string from top-level fields
uri := fmt.Sprintf("mongodb://%s:%s@%s:%v/%s",
mongoDS["username"].(string),
mongoDS["password"].(string),
mongoDS["host"].(string),
mongoDS["port"],
mongoDS["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(mongoDS["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