Skip to content

MongoDB Connection Strings in API Maker

Introduction

When connecting MongoDB to API Maker, the connection string defines how your API Maker instance communicates with your MongoDB database. Whether you’re using MongoDB Atlas, a self-hosted MongoDB instance, or a cloud provider’s managed service, the correct connection string is essential for secure and reliable data access.

In this guide, we’ll explain connection string formats, parameters, examples, troubleshooting tips, and best practices to help you integrate MongoDB with API Maker effectively.


MongoDB Connection String Format

Below is a visual breakdown of the MongoDB connection string.

mongodb[+srv]://[username:password@]host1[:port1][,host2[:port2],...]/[defaultDatabase][?options]

 └───┬─────┘  └───────┬────────┘ └───────┬────────────┘ └───────┬───────────┘ └───────┬───────────┘
     │                │                  │                      │                     │
Protocol (scheme)     │                  │                      │                     │
(mongodb or mongodb+srv)Credentials   Host(s) + Ports        Default Database      Options

MongoDB Connection String Examples

🧩 Connection String Parts Explained

  • Protocol (scheme):

    • mongodb:// → Standard connection (manual host list).
    • mongodb+srv:// → DNS seed list (Atlas, auto-discovery).
  • Credentials (optional):

    • Format: username:password@.
    • Use URL-encoding for special characters in password (p@ssp%40ss).
  • Host(s) + Ports:

    • Single host → localhost:27017
    • Multiple hosts (replica set/sharded cluster) → host1:27017,host2:27017,host3:27017
  • Default Database (optional):

    • After /, e.g., /mydb.
    • Used when none specified in queries.
  • Options (query params):

    • After ?, key-value pairs separated by &.
    • Example: ?retryWrites=true&w=majority&ssl=true

Basic Localhost Connection

mongodb://localhost:27017

Localhost with Database Name

mongodb://localhost:27017/mydb

Localhost with Username & Password

mongodb://user:password@localhost:27017/mydb

Localhost with Authentication Database

mongodb://user:password@localhost:27017/mydb?authSource=admin

Replica Set Connection

mongodb://host1:27017,host2:27017,host3:27017/mydb?replicaSet=myReplicaSet

Connection with SRV Record (Atlas)

mongodb+srv://cluster0.mongodb.net/mydb

Atlas with Username & Password

mongodb+srv://user:[email protected]/mydb

Connection with SSL/TLS Enabled

mongodb://user:password@localhost:27017/mydb?ssl=true

Connection with Retry Writes

mongodb+srv://user:[email protected]/mydb?retryWrites=true&w=majority

Connection with Read Preference

mongodb://user:password@localhost:27017/mydb?readPreference=secondary

Connection with Write Concern

mongodb://user:password@localhost:27017/mydb?w=majority&wtimeoutMS=5000

Connection with Connection Pool Size

mongodb://user:password@localhost:27017/mydb?maxPoolSize=50&minPoolSize=5

Connection with Timeouts

mongodb://user:password@localhost:27017/mydb?connectTimeoutMS=3000&socketTimeoutMS=5000

Advanced Atlas Example with Multiple Options

mongodb+srv://user:[email protected]/mydb?retryWrites=true&w=majority&readPreference=secondaryPreferred&connectTimeoutMS=10000

Complex Replica Set with SSL, Pooling & App Name

mongodb://user:password@host1:27017,host2:27017,host3:27017/mydb?replicaSet=myReplicaSet&ssl=true&maxPoolSize=100&appName=MyApp&authSource=admin

Connection string parts breakdown

Part Description Example
Scheme Protocol prefix: mongodb:// (manual hosts) or mongodb+srv:// (DNS SRV). mongodb://, mongodb+srv://
Username (optional) Database username for authentication. user
Password (optional) Password for authentication (URL-encoded if special chars). p%40ss for p@ss
@ Separator between credentials and host(s). user:password@
Host(s) One or more MongoDB server addresses. localhost, cluster0.mongodb.net
defaultauthdb Default authentication database (often admin).
Port (optional) Port number (default: 27017). :27017
Comma-separated Hosts Multiple hosts for replica sets or sharded clusters. host1:27017,host2:27017,host3:27017
/ (slash after hosts) Separator between hosts and default database. /
Default Database Database to connect to if none specified in queries. mydb
?options (query params) Connection options in key=value format (chained with &). ?retryWrites=true&w=majority

Connection string options breakdown and explanation

Parameter Description Example Value
authSource Database to authenticate against (default: admin). authSource=admin
replicaSet Name of the replica set to connect to. replicaSet=myReplicaSet
ssl / tls Enable SSL/TLS for connections. ssl=true
retryWrites Enables retryable writes (recommended for MongoDB Atlas). retryWrites=true
w Write concern (acknowledgement level for writes). w=majority, w=1
wtimeoutMS Timeout (ms) for write concern acknowledgment. wtimeoutMS=5000
readPreference Which members to read from (primary, secondary, nearest). readPreference=secondary
maxPoolSize Maximum number of connections in the connection pool. maxPoolSize=100
minPoolSize Minimum number of connections in the pool. minPoolSize=5
connectTimeoutMS Maximum time (ms) to wait for a connection. connectTimeoutMS=3000
socketTimeoutMS Timeout (ms) for socket inactivity before closing. socketTimeoutMS=5000
appName Custom name for the application (useful for monitoring in MongoDB logs). appName=MyApp
readConcernLevel Level of isolation for reads (local, majority, linearizable). readConcernLevel=majority
tlsCAFile Path to Certificate Authority (CA) file for TLS validation. tlsCAFile=/etc/ssl/ca.pem
tlsCertificateKeyFile Path to TLS key+cert file for client authentication. tlsCertificateKeyFile=/etc/ssl/mongodb.pem
compressors Enable network compression (zlib, snappy, zstd). compressors=zlib
journal If writes should be committed to the journal. journal=true
directConnection Connect directly to a single host, bypassing replica set discovery. directConnection=true
srvMaxHosts Limits the number of hosts when using mongodb+srv. srvMaxHosts=3

Secure Connection Best Practices

  • Always use SRV connection strings for MongoDB Atlas.

  • Enable SSL/TLS to encrypt data in transit.

  • Avoid hardcoding credentials in code. Use API Maker Secrets Management.

  • Restrict database user permissions to only what’s necessary.

  • Use environment variables to manage sensitive credentials.


Connecting MongoDB in API Maker

  1. Go to API Maker Secret Management > Default.

  2. Choose MongoDB as the database type.

  3. Paste your connection string.

  4. Test the connection to verify credentials and permissions.

Once connected, you can:

  • Create schemas for collections.

  • Use /api/schema/... endpoints for optimized queries.

  • Leverage Deep Populate to join MongoDB with other databases.


Troubleshooting

When connecting to MongoDB (local, self-hosted, or cloud like Atlas), you may encounter several common errors.
Below is a categorized list with explanations:

🔑 Authentication & Authorization Errors

Error Code Name Description Common Fix
2 BadValue Invalid parameter or option. Check query syntax or field types.
13 Unauthorized User lacks required permissions. Grant appropriate roles with db.grantRolesToUser.
18 AuthenticationFailed Invalid username/password. Verify credentials and authentication database.
8000 AtlasError (generic) MongoDB Atlas returned a generic error. Check Atlas logs for specific issue.
8001 AtlasUnauthorized Atlas rejected request due to insufficient privileges. Verify API key/permissions in Atlas.
403 Forbidden Attempted action not allowed by access rules. Grant required permissions.

🗂️ Duplicate & Index Errors

Error Code Name Description Common Fix
11000 DuplicateKey Duplicate value for unique index. Use unique values or handle duplicates.
11001 DuplicateKey (legacy) Same as 11000 (deprecated). Same as above.
12582 IndexOptionsConflict Conflicting index options. Drop/recreate index with correct options.

🌐 Network & Connectivity Errors

Error Code Name Description Common Fix
6 HostUnreachable Target host unreachable. Check server availability & firewall settings.
7 HostNotFound Host/DNS cannot be resolved. Verify hostname in connection string.
89 NetworkTimeout Request timed out due to slow/unavailable server. Increase timeout or fix connectivity issues.
9002 ExceededTimeLimit Request exceeded maximum allowed network time. Optimize queries, check latency.
10107 NotMaster Node is not primary, write attempted on secondary. Direct writes to primary or enable readPreference.
13436 NotPrimaryNoSecondaryOk No primary or secondary available. Ensure replica set health, retry connection.

⚡ Write & Transaction Errors

Error Code Name Description Common Fix
50 ExceededTimeLimit Operation exceeded allowed time. Optimize query or increase timeout.
91 ShutdownInProgress Operation interrupted (server shutdown). Retry after server restarts.
112 WriteConflict Write conflict in transaction. Retry operation.
11600 InterruptedAtShutdown Operation stopped during shutdown. Retry after restart.
11601 Interrupted Operation manually interrupted. Retry operation.
64 WriteConcernFailed Write concern not satisfied. Increase replication factor or adjust WC.
10990 TransactionAborted Transaction aborted due to conflict or error. Retry transaction.
251 NoSuchTransaction Transaction ID not found (expired or invalid). Ensure valid transaction session.
263 TooManyTransactions Too many open transactions. Limit concurrent transactions.

🗄️ Query & Cursor Errors

Error Code Name Description Common Fix
59 CommandNotFound Command not recognized. Use valid MongoDB command.
120 IllegalOperation Operation not valid in this context. Ensure operator/command is used correctly.
133 CursorNotFound Cursor no longer exists. Rerun query or keep cursor alive.
13127 IndexNotFound Attempt to use non-existent index. Ensure index exists or create required one.
17287 CannotImplicitlyCreateCollection Operation tried to create collection implicitly. Explicitly create collection first.
17399 BSONObjectTooLarge BSON document exceeds maximum size (16MB). Break document into smaller chunks.

🔒 TLS/SSL & Security Errors

Error Code Name Description Common Fix
8000 AtlasError Generic MongoDB Atlas error. Check Atlas logs for detailed cause.
9001 SocketException Network socket failure. Check network, TLS config, and cluster health.
11002 StaleShardVersion Outdated shard metadata used in request. Refresh shard routing info / retry operation.

🛠️ Miscellaneous Errors

Error Code Name Description Common Fix
26 NamespaceNotFound Collection/DB does not exist. Create DB/collection before querying.
43 CursorInUse Cursor already in use. Use new cursor or close previous one.
60 DatabaseDifferCase DB names differ only by letter case. Use consistent casing in DB names.
174 OutOfDiskSpace Server ran out of disk space. Free space or resize storage.
140 MapReduceError Error while running MapReduce job. Debug MapReduce functions.
17280 CappedPositionLost Attempted to query capped collection past position. Adjust query logic.
8002 AtlasClusterPaused Cluster is paused (Atlas free tier auto-pause). Resume cluster in Atlas dashboard.

🔒 Sharding & Replica Errors

Error Code Name Description Common Fix
148 StaleConfig Cluster config is outdated. Refresh cluster metadata.
13388 SendStaleConfig Shard config mismatch during request. Retry operation, ensure cluster stability.
13435 NotMasterOrSecondary Node is neither primary nor secondary. Retry on valid node.

🧩 Error Types Summary

Category Typical Causes Example Error Codes
Authentication & Authorization Invalid login, insufficient privileges, Atlas access issues 2, 13, 18, 403, 8000, 8001
Duplicate & Index Duplicate key insert, conflicting or missing indexes 11000, 11001, 12582, 13127
Network & Connectivity Host unreachable, DNS issues, timeouts, replica set errors 6, 7, 89, 9002, 10107, 13436
Write & Transaction Write concern not met, transaction aborts, conflicts 50, 64, 91, 112, 10990, 251, 263
Query & Cursor Invalid commands, lost cursors, BSON/document issues 59, 120, 133, 17287, 17399
Sharding & Replica Set Stale configs, invalid primary/secondary nodes 148, 13388, 13435, 11002
TLS/SSL & Security Socket/TLS handshake errors, invalid certificates 9001, 8000, 8002
Miscellaneous Missing namespace, disk issues, capped collections, MapReduce errors 26, 43, 60, 140, 174, 17280
  • Authentication now includes extended Atlas-specific codes (8000, 8001, 403).
  • Network extended with replica set errors like 10107 (NotMaster).
  • Transactions expanded with codes like 251 (NoSuchTransaction) and 263 (TooManyTransactions).
  • Query extended with large BSON errors (17399).
  • Sharding errors clarified with stale config and replica role mismatches.
  • Miscellaneous now includes capped collection and cluster pause errors.

FAQ

Q1: Can I use MongoDB Atlas free tier with API Maker?
Yes, the free tier works perfectly with API Maker.

Q2: What’s the difference between mongodb:// and mongodb+srv?
mongodb:// is a standard format, while mongodb+srv:// uses DNS SRV records for simplified configuration.

Q3: Does API Maker support replica sets?
Yes, simply include the replica set name in the connection string options.



List of all MongoDB cloud service providers

MongoDB Atlas (by MongoDB Inc.)

  • Official managed service by MongoDB.
  • Runs on AWS, Azure, and Google Cloud.
  • Features: auto-scaling, backup/restore, global clusters, built-in security, charts & BI connector.
  • https://www.mongodb.com/atlas

API Maker Cloud

  • Provides one click mongodb installation with latest versions.
  • Runs on dedicated VPS of your choice, so you can select based on your budget.
  • You can install MongoDB with API Maker's server also which saves a lot of money.
  • It is great choice for self hosted MongoDB, you can scale up or down mongodb server anytime you want, to handle more load and more users.
  • https://cloud.apimaker.dev

Amazon DocumentDB (with MongoDB compatibility)

  • Managed service by AWS.
  • Compatible with MongoDB APIs (not 100% feature identical).
  • Fully integrated with AWS ecosystem (IAM, VPC, CloudWatch).
  • https://aws.amazon.com/documentdb/

Azure Cosmos DB (MongoDB API)


Google Cloud (via MongoDB Atlas partnership)

  • Google Cloud does not provide a native MongoDB API service.
  • Instead, MongoDB Atlas is available directly through GCP Marketplace.
  • https://cloud.mongodb.com

ScaleGrid

  • Fully managed database hosting (MongoDB, Redis, MySQL, PostgreSQL).
  • Supports hosting on AWS, Azure, GCP, DigitalOcean.
  • Features: custom backups, dedicated servers, SSH access.
  • https://scalegrid.io/mongodb/

ObjectRocket (by Rackspace)


Aiven

  • Open-source database as a service provider.
  • Offers fully managed MongoDB alongside PostgreSQL, Kafka, Redis, etc.
  • Runs on AWS, Azure, GCP, DigitalOcean, UpCloud.
  • https://aiven.io/mongodb

IBM Cloud Databases for MongoDB


DigitalOcean Managed MongoDB

  • Simple, developer-friendly managed MongoDB clusters.
  • Built-in metrics, automated backups, scaling.
  • Popular with startups and indie developers.
  • https://www.digitalocean.com/mongodb

Kamatera


Severalnines (ClusterControl)

  • Provides automation and management for MongoDB clusters.
  • Self-hosted + managed options.
  • Features: backup, scaling, monitoring, cluster management.
  • https://severalnines.com/mongodb

Compose (Legacy - Now Part of IBM Cloud)

  • Originally independent MongoDB hosting provider.
  • Acquired by IBM, now integrated with IBM Cloud Databases.
  • Still used by some legacy users.
  • https://www.compose.com/

Bitnami (MongoDB Helm Charts / Containers)

  • Not a hosted service but widely used for self-managed MongoDB deployments.
  • Offers Helm charts and container images for Kubernetes and cloud providers.
  • Good for developers who want full control over hosting.
  • https://bitnami.com/stack/mongodb

ScaleXtremeDB (via VMWare Tanzu / PaaS integrations)

  • Provides MongoDB deployments via Kubernetes & Tanzu integrations.
  • Targets enterprises using hybrid-cloud setups.
  • https://tanzu.vmware.com

CloudClusters (MongoDB-as-a-Service)

  • Offers managed MongoDB hosting on dedicated instances.
  • Affordable developer-friendly pricing.
  • Features: automated backups, scaling, SSL, monitoring.
  • https://www.cloudclusters.io/mongodb

Instaclustr (by NetApp)

  • Managed data platform provider.
  • Supports MongoDB along with Cassandra, PostgreSQL, Kafka, Redis.
  • Strong focus on SLA-backed enterprise deployments.
  • https://www.instaclustr.com/mongodb/

ObjectBox (Edge/IoT MongoDB Alternative)


Crunchy Bridge (Postgres-first but with MongoDB compatibility layers)

  • Focused on PostgreSQL primarily, but offers tools/plugins for MongoDB interoperability.
  • Sometimes chosen for migration paths.
  • https://www.crunchydata.com/

Private Cloud / Kubernetes-based MongoDB Operators

  • Not exactly SaaS, but widely adopted for MongoDB “cloud-like” experience:
  • Ideal for enterprises who want self-managed MongoDB cloud in their private infra.

OVHcloud – Databases for MongoDB

  • https://us.ovhcloud.com/public-cloud/mongodb/
  • A true turn-key managed MongoDB DBaaS in OVH’s Public Cloud. Automates setup, maintenance, backups, elasticity, and security. Includes a free “Discovery” tier and paid production plans.

Yandex Cloud – Managed Service for MongoDB

  • https://cloud.yandex.com/services/mongodb
  • A fully managed MongoDB service within Yandex Cloud, ideal for users in CIS regions seeking low-latency or localized deployments. (Note: Yandex Cloud support info inferred; page referenced in our ecosystem but no detailed site snippet)

Clever Cloud – Managed MongoDB Add-on

  • https://www.clever-cloud.com/
  • Offers a MongoDB-managed add-on with a free 500 MB plan—good for developers wanting seamless hosting with no overhead.

Instaclustr


CloudClusters (MongoDB-as-a-Service)


Rackspace Cloud (via MongoLab Legacy)

  • [Website](http://www.rackspace.com](Website](http://www.rackspace.com)
  • Historically provided MongoDB through the MongoLab add-on in Rackspace’s cloud offerings. Now largely defunct since mLab’s acquisition by MongoDB.

mLab (now legacy / absorbed)

  • https://mlab.com/
  • Was a popular MongoDB-as-a-Service provider (formerly MongoLab), hosted on AWS, GCP, Azure, and PaaS like Heroku. Acquired by MongoDB Inc.; now users are migrated to Atlas.

Linode Managed MongoDB Service

  • Yes — Linode offers a managed MongoDB service as part of its Managed Databases portfolio.
  • Details:
    • This is powered by Akamai’s Linode Managed Database offering and includes support for MongoDB, along with MySQL, PostgreSQL, and Redis.
    • It's a true DBaaS (Database-as-a-Service) — developers can provision MongoDB clusters directly from the Linode control panel.
  • Website: https://www.linode.com/products/databases/

A2 Hosting

  • https://www.a2hosting.com/
  • Offers fully-managed MongoDB instances via their shared or VPS hosting. Geared toward users looking for low-cost, reliable MongoDB hosting with 24/7 support.

Verpex Hosting

  • https://www.verpex.com/
  • Cloud hosting solutions suitable for MongoDB deployments. While not a native DBaaS, it delivers quick setup and reliable performance for MongoDB instances.

CoreWeave

  • https://www.coreweave.com/
  • Originally focused on GPU and HPC workloads, CoreWeave provides flexible infrastructure where MongoDB can be deployed manually. Great for AI/ML teams needing both compute and database hosting.

Paperspace

  • https://www.paperspace.com/
  • Known for AI-focused cloud services, Paperspace lets developers spin up MongoDB manually on its VMs. Best suited for developers combining MongoDB with ML workflows.

RunPod

  • https://www.runpod.io/
  • AI-oriented cloud provider that also allows manual deployments of MongoDB. Popular among ML/AI startups needing fast infra with flexible pricing.

Jelastic (by Virtuozzo)

  • https://www.virtuozzo.com/
  • A multi-cloud PaaS that supports running MongoDB as a containerized or Kubernetes service. Good for developers who want scalability without full DBA overhead.

A2 Hosting

  • https://www.a2hosting.com/
  • Offers MongoDB hosting on VPS and dedicated servers. Known for speed optimization and developer-friendly setup with 24/7 support.

Verpex Hosting

  • https://verpex.com/
  • Provides cloud hosting with support for MongoDB. Simple deployment, SSD storage, and global reach for small to medium projects.

FastHosts

  • https://www.fasthosts.co.uk/
  • UK-based hosting provider. While not offering managed MongoDB, its VPS and cloud solutions are commonly used to deploy MongoDB manually.

DreamHost (VPS)

  • https://www.dreamhost.com/
  • Popular US-based hosting provider that supports MongoDB on VPS and dedicated servers. Developer-focused with open-source friendly policies.

GreenGeeks

  • https://www.greengeeks.com/
  • Eco-friendly hosting provider. Supports MongoDB deployment on VPS servers. Marketed toward small businesses and startups.

Namecheap (VPS Hosting)

  • https://www.namecheap.com/
  • Known mostly for domains, but also offers VPS hosting where MongoDB can be installed. Affordable entry point for small MongoDB workloads.

DigitalOcean (Managed Databases for MongoDB)


FastComet

  • https://www.fastcomet.com/
  • Provides MongoDB hosting on its VPS and cloud hosting plans. Known for excellent customer support, SSD storage, and developer-friendly environments.

Bluehost

  • https://www.bluehost.com/
  • Popular hosting provider that supports MongoDB on VPS and dedicated hosting. Ideal for small businesses or developers wanting MongoDB alongside websites/apps.

Ultahost

  • https://ultahost.com/
  • Offers secure and high-performance VPS hosting optimized for MongoDB. Includes free SSL, backups, and 24/7 support.

InterServer

  • https://www.interserver.net/
  • Budget-friendly VPS hosting provider with support for MongoDB. Pay-as-you-go pricing model and customizable configurations.

IONOS by 1&1

  • https://www.ionos.com/
  • Affordable VPS hosting service supporting MongoDB deployments. Popular in Europe for cost-effective and reliable infrastructure.

Vultr

  • https://www.vultr.com/
  • Cloud infrastructure provider with powerful VPS solutions. Developers often use Vultr for manually hosting MongoDB with global data center options.

Hetzner

  • https://www.hetzner.com/
  • German hosting and cloud provider. Offers affordable cloud servers widely used in Europe for hosting MongoDB clusters manually.

Scaleway

  • https://www.scaleway.com/
  • European cloud provider offering flexible cloud instances. While not a managed MongoDB service, it’s widely used for deploying MongoDB manually.

UpCloud

  • https://www.upcloud.com/
  • High-performance cloud servers with 100% uptime SLA. Developers deploy MongoDB manually on its ultra-fast VPS.