Skip to main content

Connect to MongoDB

MongoDB is a document-oriented NoSQL database that stores data as flexible JSON-like documents.

After you create a MongoDB resource in Retool, you can:

  • Query collections with filters, projections, and sort options.
  • Insert, update, and delete documents.
  • Run aggregation pipelines to transform and analyze data.
  • Execute bulk write operations across multiple collections.
  • List collections and run raw database commands.

Before you begin

To connect MongoDB to Retool, you need the following:

  • MongoDB server: Version 3.6 or later.
  • Credentials: A username and password with appropriate permissions, or a connection string that includes authentication.
  • Network access: Your MongoDB server must accept connections from Retool's IP addresses.
  • Retool permissions: Ability to create and manage resources in your organization.

Create a MongoDB resource

Follow these steps to create a MongoDB resource in your Retool organization.

1. Create a new resource

In your Retool organization, navigate to Resources in the main navigation and click Create newResource. Search for "MongoDB" and click the MongoDB tile to begin configuration.

MongoDB resource selection.

Use folders to organize your resources by team, environment, or data source type.

2. Configure general settings

Specify a name and description for the resource. The description provides more context to users and Assist about how to use the resource.

Example nameExample description
User databaseMongoDB database containing user profiles and preferences.
Product catalogRead-only MongoDB database with product and inventory data.

Mongo version

Select the connector version that matches your MongoDB server.

OptionDescription
3.6 and aboveFor MongoDB server 3.6 or later. Default and recommended.
3.4 and belowLegacy connector for MongoDB server 3.4.

Support for MongoDB server version 3.4 and earlier (3.4 and below) is deprecated and will be removed in a future release. Use 3.6 and above for all MongoDB resources.

3. Configure connection settings

Configure the connection settings for your MongoDB resource.

MongoDB connection settings.

You can autofill most connection fields using a MongoDB connection string.

Connection string example
mongodb+srv://admin:password@cluster0.example.mongodb.net/mydb?retryWrites=true&w=majority

Connection format

Select the connection format that matches your MongoDB deployment.

FormatDescription
Standard (mongodb://)For direct connections to a MongoDB server. Requires a host and port.
DNS seed list (mongodb+srv://)For MongoDB Atlas and other deployments using DNS-based service discovery. SSL is enabled by default. SSH tunnel is not available with this format.

Host

The hostname or IP address of your MongoDB server. Only required when using the Standard connection format.

Example
db.example.com

Port

The port your MongoDB server listens on. Only required when using the Standard connection format. The default MongoDB port is 27017.

Default database

The name of the MongoDB database to connect to.

Connection options

Additional connection string options to customize the connection. For SSL and TLS, use the Use SSL/TLS setting under Advanced options instead.

4. Configure authentication

Enter your Database username and Database password. To use a connection string instead, click Autofill using connection string to parse credentials and connection details from a MongoDB URI.

MongoDB authentication settings.

Store credentials in configuration variables or , and reference them with embedded expressions: {{ configVar.MONGO_PASSWORD }}.

5. Configure advanced options

Configure optional settings under Advanced options.

SSL/TLS

Configuring SSL/TLS is optional but highly recommended for production deployments.

Enable Use SSL/TLS to encrypt connections between Retool and your MongoDB server. When enabled, you can configure certificate validation and provide a client certificate if required.

SSH tunnel

Connect through an SSH tunnel to reach MongoDB servers in private networks. Not available when using the DNS seed list connection format.

Enter the SSH host, port, username, and private key for your bastion server.

Outbound region

If your organization uses outbound regions, select the region that requests to MongoDB should originate from.

6. Test the connection

Click Test connection to verify Retool can connect to MongoDB. If the test fails, check the following:

  • Network access: Ensure your MongoDB server accepts connections from Retool's IP addresses (cloud) or your Retool instance's network (self-hosted).
  • Credentials: Verify the username and password are correct and the user has access to the specified database.
  • Hostname and port: Confirm the hostname is correct and MongoDB is running on the specified port.
  • Connection format: If using DNS seed list, ensure your MongoDB deployment supports mongodb+srv:// connections.
  • SSL/TLS: If your server requires SSL, enable Use SSL/TLS under Advanced options.

7. Save the resource

Click Create resource to save your MongoDB resource. You can now use it in queries across your Retool apps and automations.

Query MongoDB data

Once you've created a MongoDB resource, you can query MongoDB data in your Retool apps and automations.

Create a query

In the query editor, select your MongoDB resource and choose an action type. Retool uses MongoDB Extended JSON syntax for all query fields.

Action types

Action typeDescriptionUse case
findReturns all documents matching a filterDisplaying a list of records
findOneReturns the first document matching a filterFetching a single record
insertOneInserts a single documentCreating a new record
insertManyInserts multiple documentsBulk importing records
updateOneUpdates the first document matching a filterEditing a single record
updateManyUpdates all documents matching a filterBulk updating records
deleteOneDeletes the first document matching a filterRemoving a single record
deleteManyDeletes all documents matching a filterBulk deleting records
findOneAndUpdateFinds a document, updates it, and returns the resultAtomic read-modify operations
aggregateRuns an aggregation pipelineTransforming and summarizing data
distinctReturns distinct values for a fieldListing unique values
countCounts documents matching a filterDisplaying record counts
bulkWriteExecutes multiple write operationsComplex bulk operations
listCollectionsLists all collections in the databaseSchema inspection
commandRuns a raw database commandAdministrative operations

Query configuration fields

Action type

The MongoDB operation to perform. See action types for all available options.

Database

The database to query. Select from the dropdown or toggle to enter a value using embedded expressions.

Dynamic database
{{ select1.value }}

Collection

The collection to query. Select from the dropdown or toggle to enter a value using embedded expressions. Not shown for listCollections and command.

Dynamic collection
{{ select1.value }}

Query / Filter / Document

The filter that determines which documents to match. Labeled Query for read operations, Filter for writes, and Document for command.

filter by field value
Exact match
{ status: "active" }
filter with comparison operators
Comparison operators
{ age: { $gte: 18 }, status: { $in: ["active", "pending"] } }
filter with embedded expression
Dynamic filter from table selection
{ _id: {{ table1.selectedRow.data._id }} }

Projection

Fields to include or exclude from results. Available for find and findOne.

Include name and email, exclude _id
{ name: 1, email: 1, _id: 0 }

Sort by

Sort order for results. Available for find.

Sort by date descending
{ createdAt: -1 }

Limit

Maximum number of documents to return. Available for find. Accepts a number or embedded expression.

Skip

Number of documents to skip. Available for find and findOne. Useful for pagination.

Document

The document or documents to insert. Available for insertOne (single object) and insertMany (array).

insertOne
Insert one document
{
name: {{ textInput1.value }},
email: {{ textInput2.value }},
createdAt: new Date()
}
insertMany
Insert multiple documents
{{ table1.data.map(row => ({ name: row.name, email: row.email })) }}

Update

The update operation to apply to matching documents. Available for updateOne, updateMany, and findOneAndUpdate.

Set a field value
{ $set: { status: {{ select1.value }}, updatedAt: new Date() } }

Aggregation

The aggregation pipeline to execute. Available for aggregate. Accepts an array of pipeline stages.

Group and count by department
[
{ $match: { status: "active" } },
{ $group: { _id: "$department", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
]

Field

The field name to get distinct values for. Available for distinct.

Operations

An array of write operations for bulkWrite. Supports insertOne, updateOne, updateMany, deleteOne, deleteMany, and replaceOne.

Options

Additional options for the operation. Refer to the MongoDB Node.js driver documentation for available options per action type.

Common use cases

find and display documents in a table

Query a collection and display results in a Table component.

First, create a query named getUsers with the find action type. Set the Collection to your target collection and add a filter:

Filter
{ status: "active" }

Set Sort by to control the order:

Sort
{ createdAt: -1 }

Next, add a Table component to your app and set its Data property to {{ getUsers.data }}.

insert a document from a form

Submit a form to insert a new document into a collection.

First, add a Form component with inputs for each field you want to capture.

Next, create a query named createUser with the insertOne action type. Set the Document field to reference your form inputs:

Document
{
name: {{ textInput1.value }},
email: {{ textInput2.value }},
role: {{ select1.value }},
createdAt: new Date()
}

Then set the form's Submit button to trigger createUser on click.

update a document from a table row

Update a document when a user edits a row in a Table component.

Create a query named updateUser with the updateOne action type. Set the Filter to match the selected row:

Filter
{ _id: {{ table1.selectedRow.data._id }} }

Set the Update field to apply the changes:

Update
{ $set: {
name: {{ table1.selectedRow.data.name }},
email: {{ table1.selectedRow.data.email }},
updatedAt: new Date()
} }

Add a Save button and set its onClick event to trigger updateUser.

delete a document with confirmation

Delete a document from a collection with a confirmation step to prevent accidental deletions.

Create a query named deleteUser with the deleteOne action type. Set the Filter to match the document to delete:

Filter
{ _id: {{ table1.selectedRow.data._id }} }

Add a Delete button. In its onClick event handler, add a Confirmation dialog action before triggering deleteUser.

aggregate data for a chart

Summarize collection data using an aggregation pipeline and display results in a Chart component.

Create a query named salesByMonth with the aggregate action type:

Aggregation pipeline
[
{ $match: { status: "completed" } },
{ $group: {
_id: { $month: "$createdAt" },
total: { $sum: "$amount" }
}},
{ $sort: { "_id": 1 } }
]

Add a Chart component and set its Data property to {{ salesByMonth.data }}. Map _id to the x-axis and total to the y-axis.