Connect Retool to a self-hosted MongoDB instance using Retool's native MongoDB connector. In the Resources tab, provide your MongoDB host, port, database name, and authentication credentials. For databases behind a VPN or firewall, configure SSH tunneling in the resource settings. Once connected, build CRUD admin panels using MongoDB's query syntax directly in Retool's query editor — no Atlas account required.
| Fact | Value |
|---|---|
| Tool | MongoDB |
| Category | Database |
| Method | Retool Native Resource |
| Difficulty | Intermediate |
| Time required | 15 minutes |
| Last updated | April 2026 |
Why Connect Retool to Self-Hosted MongoDB?
Many engineering teams run MongoDB on their own infrastructure — EC2 instances, Kubernetes clusters, bare metal servers, or private cloud environments. This gives full control over data residency, configuration, and cost, but it also means there's no hosted management UI. Retool bridges this gap: the native MongoDB connector lets you point Retool at any accessible MongoDB instance and immediately start building collection browsers, data editors, and operational dashboards without writing application code.
The key distinction from MongoDB Atlas is the connection method. Self-hosted MongoDB uses a direct host and port connection (e.g., mongodb.internal:27017) rather than an Atlas connection string with SRV DNS resolution. For instances inside a private network — behind a VPN, in an AWS VPC, or on a private subnet — Retool supports SSH tunneling through a bastion host, eliminating the need to expose your MongoDB port to the internet. Replica set configurations are also supported for connecting to a MongoDB cluster rather than a single node.
Typical use cases include admin panels for inspecting application data stored in MongoDB, support tooling for customer-facing operations teams to look up user records and order histories, data correction tools for fixing bad documents without direct database access, and operational dashboards showing collection sizes, document counts, and aggregate metrics for engineering observability.
Integration method
Retool includes a dedicated MongoDB connector for direct connections to self-managed MongoDB instances. You provide the host, port, database name, and credentials — Retool handles the connection pooling and proxies all queries through its backend. The connector supports replica set configuration, SSH tunneling for VPC-hosted instances, TLS/SSL, and the authentication database parameter (typically admin). This page covers self-hosted MongoDB; for MongoDB Atlas cloud clusters, see the separate MongoDB Atlas integration page.
Prerequisites
- A running self-hosted MongoDB instance (version 3.6 or higher) accessible from Retool's servers
- MongoDB connection details: hostname or IP, port (default 27017), database name, and authentication credentials
- For MongoDB 4.0+: a dedicated database user with the appropriate role (readWrite on the target database)
- For VPC-hosted instances: SSH access to a bastion host with connectivity to the MongoDB instance (for SSH tunneling)
- A Retool account (Cloud or self-hosted) with permission to create Resources
Step-by-step guide
Prepare MongoDB user credentials and network access
Before configuring Retool, ensure your MongoDB instance has a dedicated user for Retool with appropriate permissions, and that the instance is reachable from Retool's servers. Create a MongoDB user for Retool. Connect to your MongoDB instance using the mongo shell or MongoDB Compass, switch to the admin database, and create a user with readWrite access on the specific database Retool needs to access. Use a strong password and store it in a password manager. For network access: - If MongoDB is on a server with a public IP: open port 27017 (or your custom MongoDB port) in the server's firewall to Retool Cloud's IP ranges: 35.90.103.132/30 and 44.208.168.68/30 (us-west-2). If using eu-central-1 Retool Cloud: 3.77.79.248/30. - If MongoDB is in a private VPC: do NOT expose port 27017 publicly. Instead, configure SSH tunneling through a bastion host (covered in Step 2). - If using self-hosted Retool in the same network as MongoDB: no firewall changes needed — Retool connects directly from your network. Also verify your MongoDB configuration file (mongod.conf). The bindIp setting controls which network interfaces MongoDB listens on. For remote connections, ensure it includes either 0.0.0.0 (listen on all interfaces) or the specific IP that Retool's traffic arrives from. Restart MongoDB after any bindIp change.
1// Create Retool user in MongoDB shell2// Run in mongo shell connected as admin3use admin4db.createUser({5 user: "retool",6 pwd: "YOUR_STRONG_PASSWORD_HERE",7 roles: [8 {9 role: "readWrite",10 db: "your_database_name"11 }12 ],13 passwordDigestor: "server"14})1516// Verify user creation:17db.getUser("retool")1819// To grant read-only access instead:20// role: "read" instead of "readWrite"Pro tip: Use readWrite role only if your Retool app needs write operations. For read-only dashboards and reporting tools, grant only the read role to reduce the risk of accidental data modification. You can always change the role later if write capability is needed.
Expected result: A MongoDB user named 'retool' exists with appropriate permissions on the target database. The MongoDB port is accessible from Retool's servers (or SSH tunnel is ready).
Configure the MongoDB Resource in Retool, including SSH tunneling for private instances
In your Retool instance, navigate to the Resources tab in the left sidebar. Click Add Resource. In the resource type list, find 'MongoDB' under the Database category. Enter a descriptive name: 'MongoDB Production' or 'App Database (MongoDB)'. In the connection settings section: - Host: the hostname or IP of your MongoDB server (e.g., mongodb.internal or 10.0.1.45) - Port: 27017 (default) or your custom port - Database Name: the name of the specific database you want Retool to access - Username: the MongoDB user you created (retool) - Password: the user's password - Authentication Database: this is a critical field. MongoDB authenticates users against a specific database. If you created the user in the admin database (which is standard), enter admin here. If you created the user in the application database itself, enter that database name. For replica set connections: check the 'Use replica set?' toggle and enter the replica set name (found in your mongod.conf under replication.replSetName, e.g., rs0). Retool will connect to the replica set and automatically route read queries to secondaries if configured. For SSL/TLS: if your MongoDB requires encrypted connections (common in production), enable 'Use SSL' and optionally provide a CA certificate for self-signed certs. For SSH tunneling (MongoDB behind a VPN or in a private subnet): enable the SSH tunnel option. Provide the bastion host's public IP or hostname, SSH port (usually 22), SSH username, and the SSH private key (paste the private key content). Retool will create an SSH tunnel through the bastion and connect to MongoDB's internal address through that tunnel. The Host field should be MongoDB's internal hostname as visible from within the bastion's network (e.g., mongodb.internal or a private IP). Click Save Changes and Retool will test the connection.
Pro tip: If MongoDB authentication fails even with correct credentials, verify the Authentication Database field. This is the most common configuration error. A user created in the admin database must authenticate against admin, not against the application database, even if readWrite access is granted on a different database.
Expected result: The MongoDB resource shows a green Connected status in the Resources list. Retool has successfully authenticated and can execute queries against the configured database.
Write MongoDB queries in Retool's query editor
Open a Retool app and create a new query. Select your MongoDB resource. Retool's MongoDB query editor exposes the core MongoDB operations: find, findOne, insert, updateOne, updateMany, deleteOne, deleteMany, aggregate, count, and distinct. For a find operation: select 'find' as the action. In the Collection field, enter your collection name. The Query field accepts a MongoDB query document as JSON — equivalent to the first argument to db.collection.find(). Use {{ }} expressions to reference Retool component values dynamically. For example, to search by email with an optional status filter: - Query: { "email": { "$regex": "{{ emailSearch.value }}", "$options": "i" } } - If statusFilter.value is not empty, add: "status": "{{ statusFilter.value }}" The Projection field controls which fields are returned (1 = include, 0 = exclude). Use projections to avoid fetching large embedded documents you don't need in your UI. The Sort field takes a sort document: { "createdAt": -1 } for newest first. Limit and Skip enable pagination: bind these to Retool's Table pagination component. For an aggregation pipeline: select 'aggregate' as the action. Enter the pipeline as a JSON array of stage objects. Each stage is a MongoDB aggregation stage like $match, $group, $sort, $project, $lookup, or $unwind. Create a JavaScript transformer to flatten or reshape the MongoDB response for display in Retool components.
1// Example 1: Find documents with dynamic filtering2// Action: find3// Collection: users4// Query (evaluates to JSON):5{6 "$and": [7 {{ emailSearch.value ? { "email": { "$regex": emailSearch.value, "$options": "i" } } : {} }},8 {{ statusFilter.value ? { "status": statusFilter.value } : {} }},9 {{ planFilter.value ? { "plan": planFilter.value } : {} }}10 ]11}12// Sort: { "createdAt": -1 }13// Limit: {{ table1.pageSize }}14// Skip: {{ table1.pageIndex * table1.pageSize }}1516// Example 2: Aggregation pipeline17// Action: aggregate18// Collection: orders19// Pipeline:20[21 { "$match": { "createdAt": { "$gte": { "$date": "{{ dateRange.startDate }}" }, "$lte": { "$date": "{{ dateRange.endDate }}" } } } },22 { "$group": { "_id": "$status", "count": { "$sum": 1 }, "revenue": { "$sum": "$total" } } },23 { "$sort": { "revenue": -1 } }24]Pro tip: In Retool's MongoDB query editor, the Query and Pipeline fields are JavaScript template literals that evaluate {{ }} expressions before sending the JSON to MongoDB. This means you can build dynamic queries using component values. Be careful with type coercion — MongoDB's $in operator expects an array, and {{ textInput.value }} returns a string, so use {{ [textInput.value] }} if you need to wrap a value in an array.
Expected result: MongoDB find queries return arrays of documents that can be bound to Table components. Aggregation queries return the pipeline result array. Counts return a numeric value for KPI cards.
Implement insert, update, and delete operations for CRUD admin panels
Retool's MongoDB connector supports all four CRUD operations. Building a complete admin panel requires understanding when to use updateOne versus updateMany, and how to structure MongoDB update operators. For update operations: Retool's MongoDB query editor exposes updateOne and updateMany actions. The Filter field specifies which documents to match (same as the Query field in find). The Update field specifies the update to apply using MongoDB update operators. The $set operator updates specific fields without replacing the entire document — this is almost always what you want in an admin tool. Using { "newValues" } without an operator would replace the entire document, potentially deleting fields the form didn't include. For insert operations: use the 'insert' action with a Document field containing the new document as JSON. Reference form component values using {{ }} expressions. MongoDB automatically adds an _id field if not provided. For delete: Retool provides deleteOne (deletes the first matching document) and deleteMany. For admin tools, deleteOne is safer — always filter by _id to ensure you're deleting only the intended document. Always chain write operations with a data refresh. In the write query's Event Handlers section: On Success → Trigger query (your find/list query to refresh the Table) and Show notification. On Failure → Show notification with the error message. Add a confirmation Modal before all delete operations — this is critical for production data safety. For updates affecting multiple fields from a form: dynamically build the $set object from changed form values using a JavaScript query rather than hardcoding each field.
1// updateOne query configuration2// Action: updateOne3// Collection: users4// Filter (match by _id):5{ "_id": { "$oid": "{{ table1.selectedRow.data._id }}" } }67// Update (use $set to update only specified fields):8{9 "$set": {10 "status": "{{ statusDropdown.value }}",11 "plan": "{{ planDropdown.value }}",12 "notes": "{{ notesInput.value }}",13 "updatedAt": { "$date": "{{ new Date().toISOString() }}" },14 "updatedBy": "{{ current_user.email }}"15 }16}1718// insertOne query configuration19// Action: insert20// Collection: users21// Document:22{23 "email": "{{ emailInput.value }}",24 "status": "active",25 "plan": "{{ planSelect.value }}",26 "createdAt": { "$date": "{{ new Date().toISOString() }}" }27}Pro tip: MongoDB's _id field is a BSON ObjectId, not a plain string. When using _id in a filter, wrap it in the { "$oid": "..." } syntax so Retool's MongoDB connector correctly converts it from a string to a BSON ObjectId. Without this wrapper, the filter will match nothing because a string never equals an ObjectId.
Expected result: Update operations modify only the specified fields in matching documents. Insert operations create new documents with MongoDB-generated _ids. Delete operations with _id filters remove the exact intended document. The Table refreshes automatically after each write operation.
Handle replica sets and monitor connection health
Self-hosted MongoDB deployments often use replica sets for high availability — a primary node handles all writes and typically reads, while secondary nodes maintain copies and can serve read traffic. Retool's MongoDB connector supports replica set connections through the dedicated replica set configuration in the resource settings. To connect to a replica set: in the Retool MongoDB resource settings, enable 'Use replica set?' and enter the replica set name (e.g., rs0). The Host field should contain one or more seed hosts from the replica set — Retool will discover the full replica set topology through these seeds. You can enter multiple hosts as a comma-separated list: mongodb1.internal:27017,mongodb2.internal:27017. Retool's connection automatically handles primary failover: if the current primary steps down (e.g., during maintenance or a network partition), Retool will reconnect to the new primary without requiring resource reconfiguration. For read preference: if your MongoDB replica set has read scaling configured (reading from secondaries), you can specify the readPreference in query options. Secondary reads reduce load on the primary but may return slightly stale data — appropriate for reporting dashboards but not for operational reads that require the latest data. If your MongoDB deployment uses authentication with a specific mechanism (SCRAM-SHA-256 is the default for MongoDB 4.0+), ensure your retool user was created with the correct authentication mechanism. MongoDB 3.x used SCRAM-SHA-1 by default. For ongoing connection health: Retool maintains a connection pool per resource. If your MongoDB instance is restarted or network connections drop, Retool automatically reconnects. If you see transient connection errors in a Retool app, try running the query again — a first-attempt error often reflects a dropped idle connection being reestablished.
1// Replica set connection configuration reference2// In Retool MongoDB resource settings:3// Host: mongodb1.internal:27017,mongodb2.internal:27017,mongodb3.internal:270174// Port: (leave blank when specifying ports in host field)5// Database Name: your_database6// Username: retool7// Password: your_password8// Authentication Database: admin9// Use replica set: enabled10// Replica Set Name: rs01112// To verify replica set status from MongoDB shell:13rs.status()14// Should show all members with health: 115// and one member with stateStr: 'PRIMARY'Pro tip: If Retool connects to a MongoDB replica set during primary failover (which can take 10-30 seconds), queries may fail with a 'not master' error. This is expected behavior during failover. Implement an error handler in your Retool app that shows a user-friendly 'Database is momentarily unavailable, please retry' message rather than displaying the raw MongoDB error.
Expected result: Retool successfully connects to the MongoDB replica set and routes queries through the primary node. Read queries return data from the connected cluster, and the connection automatically recovers after primary failover.
Common use cases
Build a collection browser and document editor for ops teams
Create a Retool app that lists all documents in a MongoDB collection with filtering by any field. Support teams can search by user ID, email, or status, view the full document in a sidebar, and edit individual fields via a form. Write operations use updateOne with $set to modify only the changed fields, preserving the rest of the document.
Build a MongoDB collection browser for the 'users' collection. Show a Table with columns for _id, email, status, createdAt, and plan. Add a search input that filters by email using a regex query. When a row is selected, show the full document as editable fields in a side panel. Include a Save Changes button that runs an updateOne with $set for only the modified fields, and a Deactivate button that sets status to 'inactive'.
Copy this prompt to try it in Retool
Create an order management dashboard with aggregation queries
Build a dashboard that runs MongoDB aggregation pipelines to calculate order metrics by date range — total orders, revenue by product category, and average order value. Display results in KPI cards and Chart components. Use Retool's JavaScript transformers to reshape aggregation results for Retool's Chart data format.
Build an order analytics dashboard that runs a MongoDB aggregation pipeline on the 'orders' collection grouping by order status and calculating total revenue and order count per status. Show results as KPI cards (total revenue, total orders, average order value) and a pie chart of orders by status. Add a date range picker that filters the aggregation to orders within the selected date range.
Copy this prompt to try it in Retool
Build an error log viewer for MongoDB-stored application logs
Create a Retool panel that queries a MongoDB logs collection for error-level entries, displays them in a Table sorted by timestamp descending, and allows support engineers to mark errors as acknowledged or resolved. Include a JSON viewer for the full log document including stack traces, context objects, and metadata.
Build an application error log viewer querying the 'logs' MongoDB collection where level equals 'error'. Show a Table with timestamp, service name, error message, and acknowledged status. Sort by timestamp descending. When a row is clicked, show the full log document as pretty-printed JSON. Include an Acknowledge button that sets acknowledged to true and acknowledged_by to the current Retool user's email.
Copy this prompt to try it in Retool
Troubleshooting
Connection fails with 'Authentication failed' or 'MongoServerError: Authentication failed' error
Cause: The username, password, or Authentication Database field in the Retool resource settings is incorrect. The most common error is leaving the Authentication Database as the application database name when the user was created in the admin database.
Solution: Verify the user exists in MongoDB by running db.getUsers() in the mongo shell on the authentication database. Confirm the password is correct. Most importantly, check the Authentication Database field in Retool — it must be the database where the user was created (usually admin for administrative users created with db.createUser() in the admin database). If unsure, check by running use admin; db.getUser('retool') in the mongo shell.
Connection times out with 'connect ETIMEDOUT' or 'MongoTimeoutError: Server selection timed out'
Cause: Retool's servers cannot reach the MongoDB host on the specified port. The server firewall blocks the connection, bindIp in mongod.conf is set to 127.0.0.1 (localhost only), or the host/port values are incorrect.
Solution: For Retool Cloud: verify the firewall allows inbound connections on port 27017 from Retool's IP ranges. Check mongod.conf and ensure bindIp includes 0.0.0.0 or the server's external IP — then restart MongoDB. Test connectivity separately before debugging Retool. For private networks, use SSH tunneling in the Retool resource settings instead of exposing MongoDB directly.
1# Check mongod.conf bindIp setting2# The net section should include your server's external IP or 0.0.0.0:3net:4 port: 270175 bindIp: 0.0.0.06 # or specify: 127.0.0.1,10.0.1.45 to bind localhost + private IPQuery returns 'MongoServerError: not authorized on databaseName to execute command' even with correct credentials
Cause: The MongoDB user has readWrite access on a different database than the one being queried, or the query is trying to access a collection in a database that the user's role doesn't cover.
Solution: In the MongoDB shell, check the user's roles: use admin; db.getUser('retool'). Verify the role includes readWrite (or read) on the exact database name being queried. If querying multiple databases, add additional role entries for each database. In Retool, the Database Name field in the resource settings sets the default database, but queries can specify a different collection — ensure the user has access to all collections being queried.
1// Grant additional database access from mongo shell:2use admin3db.grantRolesToUser(4 "retool",5 [{ role: "readWrite", db: "second_database_name" }]6)SSH tunnel connection fails with 'Authentication failed' for the tunnel itself
Cause: The SSH private key in Retool's resource settings is incorrectly formatted, truncated, or the SSH user on the bastion host does not accept key-based authentication from Retool.
Solution: Verify the private key is in PEM format (starts with -----BEGIN RSA PRIVATE KEY----- or -----BEGIN OPENSSH PRIVATE KEY-----). Copy the entire key including the header and footer lines. Test the key manually from another machine before pasting into Retool. If using a passphrase-protected key, note that Retool does not support passphrase-protected SSH keys for tunneling — generate a new key without a passphrase specifically for Retool's bastion access.
Best practices
- Create a dedicated MongoDB user for Retool with the minimum required permissions (readWrite for apps needing writes, read for dashboards) rather than using application service account credentials or admin users.
- Always specify the Authentication Database field in the Retool resource settings — mismatched authentication databases are the most common cause of MongoDB connection failures and authentication errors.
- Use SSH tunneling for any MongoDB instance in a private network rather than opening firewall rules or exposing the MongoDB port to the internet, as this is significantly more secure.
- Apply MongoDB projections in your find queries to return only the fields your Retool app needs — this reduces data transfer, improves query performance, and avoids accidentally exposing sensitive fields in Retool's response inspector.
- Always use $set in update operations to modify specific fields rather than replacing entire documents — this prevents accidentally deleting fields that exist in MongoDB but aren't represented in your Retool form.
- Wrap MongoDB _id field values in { "$oid": "string" } syntax when using them in filter queries — plain string comparisons against BSON ObjectId will always return no results.
- For replica set deployments, add multiple seed hosts (comma-separated) in the Host field so Retool can discover the full cluster even if one seed node is temporarily unavailable during maintenance.
Alternatives
MongoDB Atlas is the managed cloud version of MongoDB with IP whitelisting and Atlas connection strings — prefer it over self-hosted MongoDB when you want a fully managed database without infrastructure maintenance.
Redis is a key-value in-memory store suited for caching, sessions, and leaderboards rather than persistent document storage — use it alongside MongoDB when your Retool app needs fast lookups for ephemeral or cached data.
Amazon DynamoDB is a fully managed NoSQL database on AWS that requires no server maintenance — prefer it over self-hosted MongoDB when your application is already AWS-native and you want zero operational overhead.
Frequently asked questions
What is the difference between this MongoDB integration and the MongoDB Atlas integration?
This page covers connecting Retool to a self-managed MongoDB instance that you run on your own infrastructure — on EC2, on-premises servers, Kubernetes, or any VPC. The MongoDB Atlas integration (separate page) covers Retool's connection to MongoDB Atlas, the fully managed cloud service, which uses Atlas-specific connection strings with SRV DNS resolution and Atlas IP access list configuration instead of direct host/port access. If your team doesn't manage MongoDB infrastructure directly, you likely want the Atlas integration.
Does Retool support MongoDB 4.x, 5.x, and 6.x?
Yes. Retool's MongoDB connector uses a modern MongoDB driver compatible with MongoDB 3.6 and above, covering all current MongoDB versions (4.x, 5.x, 6.x, and 7.x). If you're running MongoDB 3.4 or earlier, you may encounter compatibility issues and should strongly consider upgrading — these versions are past end-of-life and no longer receive security patches.
Can I connect Retool to multiple MongoDB databases or collections?
Yes. A single Retool MongoDB resource connects to one MongoDB instance (host/port), but individual queries within that resource can specify different collections. For different databases on the same MongoDB instance, create separate Retool resources with the same host/port but different Database Name fields — this lets you have one resource for your users database and another for your analytics database, both connecting to the same MongoDB server.
How do I run MongoDB aggregation pipelines in Retool?
In the Retool MongoDB query editor, select 'aggregate' as the Action type. The Pipeline field accepts a JSON array of aggregation stage objects. Enter your pipeline stages ($match, $group, $sort, $project, $lookup, $unwind, etc.) as a JSON array. You can reference Retool component values using {{ }} within the pipeline — for example, { "$match": { "status": "{{ statusFilter.value }}" } } dynamically filters the aggregation based on a dropdown selection. The aggregation result is returned as an array that you can bind to Table or Chart components.
Does Retool's MongoDB integration support Change Streams for real-time updates?
No. Retool does not natively subscribe to MongoDB Change Streams. For near-real-time updates in a Retool dashboard, configure the query to auto-run on a polling interval (query Advanced settings → Run query automatically → set an interval). For truly event-driven updates, use a Retool Workflow with a webhook trigger: your application backend watches the Change Stream and calls the Retool Workflow webhook when relevant changes occur, which can then trigger notifications or update Retool state.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation