# How to Integrate Retool with MongoDB Atlas

- Tool: Retool
- Difficulty: Intermediate
- Time required: 25 minutes
- Last updated: April 2026

## TL;DR

Connect Retool to MongoDB Atlas using the native MongoDB Resource and your Atlas connection string. Authenticate with a database user, whitelist Retool's IP ranges in Atlas Network Access, and write MongoDB query syntax (find, aggregate, insertOne) directly in Retool's query editor. The most common gotcha is that the final segment of the Atlas connection string must match your actual database name — leave it as 'myFirstDatabase' and queries will fail silently.

## Why connect Retool to MongoDB Atlas?

MongoDB Atlas is a popular backend for modern applications, but Atlas's Data Explorer — its built-in document browsing UI — is limited for operational use. It lacks the ability to build filtered views, run complex aggregations with visual controls, or build forms for creating and updating documents with input validation. Retool gives MongoDB Atlas a full-featured admin interface without requiring you to build custom tooling.

The most common Retool-MongoDB Atlas use cases include customer record management (searching and editing application user documents), content moderation dashboards (reviewing user-generated content stored as documents), order management panels (filtering orders by status, date range, and amount), and data migration tools (reading from one collection and writing to another with transformations). Any workflow that requires more than basic document inspection benefits from having a Retool interface in front of Atlas.

MongoDB Atlas on Retool uses the same query syntax as MongoDB — you write find() filters, projection objects, and aggregation pipeline stages directly in the query editor. Retool's {{ }} syntax integrates seamlessly with MongoDB's BSON-compatible JSON query format, so parameterizing queries with UI component values is natural. The server-side proxy means query responses can include full documents without CORS or client exposure concerns.

## Before you start

- A MongoDB Atlas account with a cluster and at least one database containing collections
- Permissions to create database users and manage Network Access in Atlas (Project Owner or similar role)
- Your Atlas project's connection string (found in Atlas → Connect → Drivers)
- A Retool account with Resource creation permissions
- Basic familiarity with MongoDB query syntax (find filters, projection objects)

## Step-by-step guide

### 1. Whitelist Retool's IP addresses in Atlas Network Access

MongoDB Atlas blocks all inbound connections by default through its Network Access controls. Before Retool can connect to your Atlas cluster, you must add Retool's server IP ranges to the Atlas allowlist. In the Atlas console, select your Project and navigate to Security → Network Access. Click Add IP Address. Retool Cloud routes requests through two CIDR blocks depending on your Retool region: for the US (us-west-2) region, add 35.90.103.132/30 and 44.208.168.68/30. For EU (eu-central-1), add 3.77.79.248/30. For Singapore (ap-southeast-1), check Retool's current documentation for the specific IPs as they may have additional ranges. Enter each CIDR range in the IP Address field, add a descriptive comment like Retool Cloud us-west-2, and click Confirm. If you are self-hosted on Retool, you can add your own server's outbound IP address instead, which is more precise. Alternatively, if you are in a development or low-security context, you can temporarily add 0.0.0.0/0 to allow all IPs — but remove this and add specific Retool IPs before going to production. IP allowlist changes propagate in approximately 60 seconds.

**Expected result:** Retool's IP CIDR ranges appear in the Atlas Network Access allowlist with an Active status. Atlas will now accept inbound connections from Retool's servers.

### 2. Create an Atlas database user and get the connection string

In Atlas, go to Security → Database Access. Click Add New Database User. Choose Password as the authentication method. Enter a username (e.g., retool-user) and a strong password — save these securely. Under Database User Privileges, select the minimum required access: use Built-in Role → Read and write to any database for a general-purpose integration, or create a Custom Role if you want to restrict access to specific collections. Click Add User. Now get your connection string: in Atlas, click the Connect button on your cluster. Select Drivers as the connection method. Choose the Driver as Node.js and copy the connection string shown — it looks like mongodb+srv://retool-user:<password>@cluster0.abc123.mongodb.net/myFirstDatabase. Replace <password> with your actual password. CRITICAL: The final path segment myFirstDatabase is NOT a placeholder — this is the database name that Retool's connector will use for queries. Change myFirstDatabase to the actual name of the database you want to query (e.g., production, app_db, or your specific database name). Getting this wrong is the most common source of 'collection not found' errors — the connector will connect successfully but target the wrong (or nonexistent) database.

```
// Example Atlas connection string — replace ALL placeholder values
// Before:
mongodb+srv://retool-user:<password>@cluster0.abc123.mongodb.net/myFirstDatabase

// After (with correct values):
mongodb+srv://retool-user:MySecurePass123@cluster0.abc123.mongodb.net/production
//                         ↑ actual password                              ↑ actual database name
```

**Expected result:** You have a complete Atlas connection string with the correct password and database name, ready to paste into Retool.

### 3. Configure the MongoDB Resource in Retool

In Retool, go to the Resources tab and click Add Resource. Search for or scroll to MongoDB. Click it to open the configuration panel. Give the resource a descriptive name like MongoDB Atlas Production. In the Host section, Retool offers two configuration modes: Connection String mode and individual fields. Select the Connection string toggle if available, or look for the option to enter a mongodb+srv:// URI. Paste your complete Atlas connection string into the connection string field. Retool parses the hostname, username, password, and database name from the string and populates the individual fields. Verify that the Database field shows your actual database name (not myFirstDatabase). If the individual fields are shown instead of a connection string input, manually fill in: Host as your Atlas cluster hostname (e.g., cluster0.abc123.mongodb.net), Port as 27017, Database as your database name, Username and Password as your Atlas database user credentials, and enable Use SSL/TLS. Click Save. Retool tests the connection — a green Connected status confirms success. If you see a connection timeout, the most likely cause is that Retool's IPs are not yet in the Atlas Network Access allowlist (check Step 1 again).

**Expected result:** The MongoDB Resource shows Connected in Retool's Resources list. You can now create queries that read and write documents from your Atlas collections.

### 4. Write MongoDB find and filter queries

Create a new query in the Code panel, select your MongoDB resource, and explore the query interface. MongoDB queries in Retool use a structure with Collection, Operation, and operation-specific fields. Set the Collection to the name of a collection in your database (e.g., users, orders, products). Select Find as the operation. In the Filter field, enter a MongoDB filter object in JSON format. Leave it as {} to return all documents (up to the limit), or add filter criteria. Use Retool's {{ }} syntax to reference component values in filters — for example, to filter by email from a text input, use { email: {{ emailInput.value }} }. In the Projection field, specify which fields to return to reduce payload size: { _id: 1, email: 1, name: 1, status: 1, createdAt: 1 }. Set a Limit (e.g., 100) to prevent fetching millions of documents. Add a Sort object to control ordering: { createdAt: -1 } sorts newest-first. Run the query. MongoDB returns an array of document objects. Unlike SQL databases, MongoDB documents may have inconsistent field structures — if some documents have a field and others do not, the missing field will be undefined. Use a transformer to normalize documents into a consistent flat structure before binding to Table components.

```
// MongoDB find query examples for Retool's Filter field

// All documents (no filter)
{}

// Filter by exact field value (references a Retool text input)
{ "status": {{ statusDropdown.value }} }

// Filter by email (case-insensitive regex from a search input)
{ "email": { "$regex": {{ searchInput.value }}, "$options": "i" } }

// Filter by date range (references Retool DateRangePicker)
{
  "createdAt": {
    "$gte": {{ new Date(dateRange.value[0]) }},
    "$lte": {{ new Date(dateRange.value[1]) }}
  }
}

// Filter by nested field
{ "address.country": {{ countrySelect.value }} }
```

**Expected result:** The find query returns an array of matching documents. Modifying the search input value and re-running the query returns filtered results. You can see document structure in Retool's response inspector.

### 5. Run aggregation pipelines and build write operations

For analytics and complex transformations, use MongoDB's aggregation pipeline in Retool. Select Aggregate as the operation and enter a pipeline array. Each stage is a JSON object with a MongoDB operator. The pipeline runs entirely in Atlas, which is more efficient than fetching raw data and transforming it in Retool JavaScript. For write operations — creating, updating, and deleting documents — create separate queries for each operation type. Use insertOne with a Document field containing the new document object, referencing Form component values via {{ form1.data }}. Use updateOne with a Filter (to identify the document) and an Update object using MongoDB update operators like $set, $unset, and $push. For the filter, reference the selected row's ID: { _id: {{ table1.selectedRow._id }} }. Always add a Confirm dialog to delete operations. Wire all write queries to event handlers: on success, trigger the main find query to refresh the table and show a success notification. For bulk updates across many documents, use updateMany with a filter that matches multiple documents.

```
// Aggregation pipeline example — monthly order totals
// Set Operation to 'Aggregate', paste this into the Pipeline field
[
  {
    "$match": {
      "status": "completed",
      "createdAt": {
        "$gte": {{ new Date(new Date().getFullYear(), 0, 1) }}
      }
    }
  },
  {
    "$group": {
      "_id": {
        "year": { "$year": "$createdAt" },
        "month": { "$month": "$createdAt" }
      },
      "total_orders": { "$sum": 1 },
      "total_revenue": { "$sum": "$amount" },
      "avg_order_value": { "$avg": "$amount" }
    }
  },
  {
    "$sort": { "_id.year": 1, "_id.month": 1 }
  }
]
```

**Expected result:** The aggregation pipeline runs in Atlas and returns grouped, summarized data ready to bind to Chart or Table components. Write queries (insert, update, delete) execute successfully and the main query refreshes to show updated data.

## Best practices

- Always change the database name in the Atlas connection string from the default myFirstDatabase to your actual database name before saving the Retool Resource — this is the single most common configuration error.
- Create a dedicated Atlas database user for Retool with the minimum required privileges — use Built-in Role: Read and write to specific databases rather than cluster-level admin access.
- Use MongoDB's Projection field in find queries to return only the fields you need — this reduces data transfer and improves performance, especially for collections with large documents or many fields.
- Test complex aggregation pipelines in Atlas's built-in Aggregation Pipeline Builder before pasting them into Retool — Atlas provides stage-by-stage previews that help debug pipeline logic.
- Add Limit to all find queries — even in development — to avoid accidentally fetching millions of documents and hitting Retool's 100 MB response size limit.
- Use updateOne rather than replaceOne for document updates to avoid accidentally overwriting fields you did not intend to change — $set updates only specified fields while replaceOne replaces the entire document.
- For text search operations, prefer MongoDB Atlas Search (full-text search index) over $regex for production performance — $regex performs collection scans while Atlas Search uses inverted indexes.
- Use Retool Workflows for batch operations on large document sets — looping through documents in a Workflow with sequential execution and error handling is more reliable than JavaScript queries in app context.

## Use cases

### Customer records search and edit panel

Build a Retool panel that searches an Atlas users or customers collection by any combination of fields — email, name, plan tier, signup date, or custom metadata fields. Results display in a Table with inline editing for writable fields. Selecting a row opens a detail sidebar showing the full document, and operators can update nested fields through a Form component that writes back to Atlas.

Prompt example:

```
Build a Retool customer panel that queries a MongoDB Atlas 'users' collection with a search input for email and a Select for plan tier. Display results in an editable Table showing name, email, plan, and created date. When a row is selected, show the full document in a JSON viewer on the right and add an Edit button that opens a form to update fields.
```

### Order management and fulfillment dashboard

Create a Retool dashboard that queries an orders collection with filters for status (pending, processing, shipped, delivered), date range, and order value threshold. Operations teams can view order details, update order statuses, and trigger status-change events that cascade to other collections — for example, marking an order as shipped and updating the associated inventory document in the same query chain.

Prompt example:

```
Build a Retool order management panel that queries a MongoDB Atlas 'orders' collection filtered by status and date range. Show orders in a Table with order ID, customer email, total amount, and current status. Add a button to bulk-update selected orders' status and a detail panel showing line items when a row is selected.
```

### Analytics aggregation dashboard

Use MongoDB's aggregation pipeline in Retool to compute business metrics directly in Atlas — total revenue by month, active user counts by plan tier, average order values by customer segment. The aggregation pipeline runs in Atlas and returns pre-computed results, reducing the amount of data transferred. Retool's Chart components visualize the aggregated output without additional client-side computation.

Prompt example:

```
Build a Retool analytics dashboard that runs a MongoDB aggregation pipeline on an 'events' collection to group events by day and type for the last 30 days, returning daily counts per event type. Display the results in a line Chart showing event volume over time.
```

## Troubleshooting

### Connection times out with 'connect ETIMEDOUT' error

Cause: Retool's IP addresses are not in the Atlas Network Access allowlist, so Atlas's firewall is blocking the connection before authentication.

Solution: Go to Atlas → Security → Network Access and verify that Retool's CIDR ranges are listed with Active status. If you recently added them, wait 60 seconds for propagation. Also confirm you are using the correct CIDR ranges for your Retool deployment region (us-west-2, eu-central-1, or ap-southeast-1).

### Connection succeeds but queries return empty results for all collections

Cause: The database name in the Atlas connection string is incorrect — the final path segment still says myFirstDatabase or points to a database that exists but is empty.

Solution: Edit the MongoDB Resource in Retool and check the Database field. It must match the exact database name in Atlas. Go to Atlas → Browse Collections to find your actual database names. Update the connection string or the Database field to use the correct name.

```
// Correct connection string format:
// mongodb+srv://username:password@cluster.mongodb.net/YOUR_ACTUAL_DATABASE_NAME
// NOT:
// mongodb+srv://username:password@cluster.mongodb.net/myFirstDatabase
```

### Authentication failed: bad auth — MongoServerError

Cause: The username or password in the connection string is incorrect, the database user has been deleted, or the password contains special characters that were not URL-encoded.

Solution: Verify the database user exists in Atlas → Security → Database Access. If the password contains special characters (@, :, /, ?, #), URL-encode them — for example, @ becomes %40. The easiest fix is to create a new database user with a password that uses only alphanumeric characters, then update the connection string in Retool.

### Aggregation pipeline query returns an error about operator syntax

Cause: MongoDB aggregation pipeline syntax in Retool requires the pipeline to be a valid JSON array — JavaScript-style operators like $gte with Date() constructors may not parse correctly as static JSON.

Solution: For pipelines that need dynamic values (date ranges, user inputs), use Retool's {{ }} syntax to inject the values. Use ISO date strings rather than Date() constructors in the JSON — Retool evaluates {{ new Date(dateInput.value).toISOString() }} as a string, which MongoDB accepts for date comparisons.

```
// Use ISO date strings instead of Date() constructors in aggregation
// Problematic:
{ "$gte": { "$date": new Date("2024-01-01") } }

// Working in Retool:
{ "$gte": {{ new Date(dateRangePicker.value[0]).toISOString() }} }
```

## Frequently asked questions

### Why does my query connect successfully but return empty results?

The most likely cause is an incorrect database name in your Atlas connection string. The final segment of the mongodb+srv:// URL (e.g., /myFirstDatabase) must exactly match your actual database name. Open Atlas, go to Browse Collections, check the database name on the left sidebar, and update the connection string or the Database field in the Retool Resource to match.

### Can I use MongoDB ObjectId (_id) values in Retool filter queries?

Yes, but with care. MongoDB ObjectIds are BSON types, not plain strings. In Retool's query filter field, reference an ObjectId using the $oid syntax: { _id: { $oid: '{{ table1.selectedRow._id }}' } }. If you store _id as a string in your collection rather than ObjectId, you can filter it like any other string field. Check your collection's document schema in Atlas to confirm the _id type.

### Does Retool support MongoDB transactions?

Retool's native MongoDB connector does not expose multi-document transaction support in its query editor UI. For operations that require ACID transactions (e.g., debiting one account and crediting another atomically), use a Retool Workflow with a JavaScript code block that uses the MongoDB Node.js driver's session and transaction APIs via a REST API call to your backend, or implement the logic as a server-side function and call it from Retool.

### How do I handle large MongoDB collections with millions of documents in Retool?

Always use indexed fields in your filter queries — unindexed searches on large collections cause slow queries and Atlas resource spikes. Set a Limit on all find queries and implement Retool's Table pagination using skip and the limit value. For aggregation queries on large collections, use $match as the first pipeline stage to filter early before expensive $group or $lookup stages, and ensure your match fields are indexed.

### Can Retool connect to MongoDB Atlas free tier clusters?

Yes. Atlas free tier (M0) clusters support standard MongoDB connections including the mongodb+srv:// connection string format that Retool uses. The main limitation is that Atlas M0 does not support IP allowlisting with custom CIDR ranges — you can only allow access from anywhere (0.0.0.0/0). For production use with specific IP whitelisting, upgrade to an M10 or higher paid cluster.

---

Source: https://www.rapidevelopers.com/retool-integrations/mongodb-atlas
© RapidDev — https://www.rapidevelopers.com/retool-integrations/mongodb-atlas
