Skip to main content

MongoDB Configuration

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

Connection Parameters

Required Fields

FieldDescriptionExample
HostDatabase hostnamemongodb.example.com
PortMongoDB port (default: 27017)27017
DatabaseDatabase namemyapp

Optional Fields

FieldDescriptionExample
UsernameFor authenticated connectionsapp_user
PasswordAuthentication password
Connection OptionsQuery parametersauthSource=admin&replicaSet=rs0
Use SSL/TLSEnable for encrypted connections

Configuration Example

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

FieldExample ValueNotes
Data source labelprod-mongodbKebab-case unique identifier (used as both name and label)
Hostmongodb.example.comDatabase hostname
Port27017Default MongoDB port
DatabasemyappDatabase name
Usernameapp_userOptional for auth
PasswordpasswordOptional, encrypted at rest
Connection OptionsauthSource=adminOptional query parameters
Use SSL/TLSEnabledRecommended 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 tables field 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:

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