> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloudthinker.io/llms.txt
> Use this file to discover all available pages before exploring further.

# MongoDB

> Connect MongoDB databases to CloudThinker for document query analysis, performance tuning, and operational insights

Connect your MongoDB databases to enable [Tony](/guide/agents/tony) (Database Engineer) to analyze queries, optimize performance, and monitor database health.

## Supported platforms

| Platform                | Support            |
| ----------------------- | ------------------ |
| **Self-hosted MongoDB** | 4.x, 5.x, 6.x, 7.x |
| **MongoDB Atlas**       | All versions       |

## Prerequisites

* A MongoDB instance or Atlas cluster reachable from CloudThinker over the network.
* Admin access to create a dedicated database user and assign roles.
* The MongoDB connection string with credentials.

## Setup

Select your MongoDB platform for specific connection instructions.

<Tabs>
  <Tab title="Self-hosted MongoDB">
    <Steps>
      <Step title="Connect as admin">
        Connect to your MongoDB instance using the Mongo shell (`mongosh`) with administrative privileges.

        *Replace `<admin-user>`, `<admin-password>`, and `<your-host>` with your credentials. The `/admin` database is required.*

        ```bash theme={null}
        mongosh "mongodb://<admin-user>:<admin-password>@<your-host>:27017/admin"
        ```
      </Step>

      <Step title="Switch to the admin database">
        Ensure you are on the `admin` database where users are created:

        ```javascript theme={null}
        use admin
        ```
      </Step>

      <Step title="Create a read-only user">
        Create a dedicated user for CloudThinker using standard MongoDB built-in roles:

        ```javascript theme={null}
        db.createUser({
          user: "<cloudthinker_user>",
          pwd: "<secure-password>",
          roles: [
            { role: "readAnyDatabase", db: "admin" },
            { role: "clusterMonitor", db: "admin" }
          ]
        })
        ```

        The `clusterMonitor` role is recommended for performance metrics analysis.
      </Step>

      <Step title="Configure network access">
        Ensure CloudThinker can reach your database:

        * Add CloudThinker IPs to your firewall or security group
        * Ensure MongoDB is bound to an accessible IP address in `mongod.conf`
      </Step>

      <Step title="Add the connection in CloudThinker">
        Navigate to **Connections → MongoDB** and paste your connection string:

        ```
        mongodb://<cloudthinker_user>:<secure-password>@<your-host>:27017/admin?tls=true&appName=CloudThinker
        ```

        Include `tls=true` if your deployment enforces TLS encryption. Click **Connect**. CloudThinker shows a **Connected** status once it succeeds.
      </Step>
    </Steps>
  </Tab>

  <Tab title="MongoDB Atlas">
    <Steps>
      <Step title="Navigate to Database Access">
        Log in to your MongoDB Atlas dashboard at [cloud.mongodb.com/v2](https://cloud.mongodb.com/v2).

        From the left sidebar, scroll down to the **Security** section and select **Database Access**.
      </Step>

      <Step title="Add a new database user">
        Click **Add New Database User** and configure the following:

        * **Authentication Method**: Password
        * **Username**: `<cloudthinker_user>`
        * **Password**: generate a secure password
        * **Database User Privileges**: select **Built-in Role** → **Read Any Database**

        Click **Add User**.
      </Step>

      <Step title="Configure network access">
        Navigate to **Network Access** under the **Security** section:

        * Click **IP Access List** → **+ Add IP Address**
        * Enter the CloudThinker static IP addresses shown on the CloudThinker connection setup screen
        * Add a comment such as `CloudThinker Agent Access` for future auditing
        * Click **Confirm**
      </Step>

      <Step title="Get the connection string">
        Navigate to the **Databases** tab (under **Deployment**), click **Connect** on your cluster, and choose **Drivers**.

        Atlas provides a string in this format:

        ```
        mongodb+srv://<username>:<password>@<cluster-name>.<cluster-hash>.mongodb.net/?appName=<ClusterName>
        ```

        Customize it for CloudThinker:

        ```
        mongodb+srv://<cloudthinker_user>:<secure-password>@<cluster-name>.<cluster-hash>.mongodb.net/admin?appName=CloudThinker&tls=true&retryWrites=false
        ```

        * `/admin` explicitly specifies the authentication database
        * `appName=CloudThinker` makes it easy to identify in your database logs
        * `tls=true` enforces encryption in transit
        * `retryWrites=false` is appropriate for this read-only user
      </Step>

      <Step title="Add the connection in CloudThinker">
        Navigate to **Connections → MongoDB** and paste your customized connection string. Click **Connect**. CloudThinker shows a **Connected** status once it succeeds.
      </Step>
    </Steps>
  </Tab>
</Tabs>

## Connection details

| Field                  | Description                                                | Example                                       |
| ---------------------- | ---------------------------------------------------------- | --------------------------------------------- |
| **Connection string**  | Full MongoDB URI including credentials                     | `mongodb+srv://user:pass@host/admin?tls=true` |
| **TLS/SSL**            | Enforce TLS for the connection — use `tls=true` in the URI | `true`                                        |
| **Read preference**    | Which nodes to route read operations to                    | `primary`                                     |
| **Connection timeout** | Seconds to wait for connection                             | `10`                                          |

## Required permissions

| Role              | Purpose                                                                                          |
| ----------------- | ------------------------------------------------------------------------------------------------ |
| `readAnyDatabase` | Analyze queries and index usage across all collections                                           |
| `clusterMonitor`  | Access `serverStatus`, `replSetGetStatus`, and other diagnostic commands for performance metrics |

<Tip>
  Assign both roles to unlock full query analysis and cluster health monitoring. Never grant write or admin roles to the CloudThinker user.
</Tip>

## Agent capabilities

Once connected, Tony can:

| Capability                | Description                                                     |
| ------------------------- | --------------------------------------------------------------- |
| **Query analysis**        | Identify slow queries, analyze execution plans with `explain()` |
| **Index recommendations** | Find missing indexes, identify unused indexes                   |
| **Performance metrics**   | Monitor connections, memory usage, and replication lag          |

### Verify the connection

```text theme={null}
@tony #report list all MongoDB databases and summarize their collection counts
```

### Example prompts

```text theme={null}
@tony #report analyze slow queries on the production MongoDB instance
@tony #recommend find missing indexes on the users collection
@tony #report check replication lag on the secondary nodes
```

## Troubleshooting

<Accordion title="Authentication failed">
  * Verify username and password are correct
  * Ensure the user is created on the `admin` database, or append `?authSource=admin` to your connection string
  * For Atlas: confirm the user was created with the correct privileges under Database Access
</Accordion>

<Accordion title="Connection refused or timeout">
  * Check that CloudThinker IPs are added to your Atlas Network Access list or your firewall
  * For local MongoDB, ensure `bindIp` in `mongod.conf` is not set to only `127.0.0.1`
</Accordion>

<Accordion title="Performance metrics unavailable">
  * Tony needs the `clusterMonitor` role to run `serverStatus` and `replSetGetStatus`
  * Add the `clusterMonitor` role to the CloudThinker user on the `admin` database and reconnect
</Accordion>

## Security

* **Least privilege** — grant only the permissions the agents need for your use case; start read-only and widen later.
* **Read-only by default** — use read-only credentials unless you want agents to make changes through this connection.
* **Rotate credentials** — rotate keys and tokens on your normal schedule; CloudThinker picks up the new value when you update the connection.
* **Revoke on offboarding** — remove the credential at the provider when you delete a connection or a teammate leaves.

- **TLS required** — always use `tls=true` in the connection string to encrypt data in transit.
- **Minimal roles** — grant only `readAnyDatabase` and `clusterMonitor`; never grant write or admin roles.

## Related

<CardGroup cols={2}>
  <Card title="Tony Agent" icon="database" href="/guide/agents/tony">
    Database-focused optimization agent
  </Card>

  <Card title="PostgreSQL Connection" icon="https://mintcdn.com/cloudthinker/aLd-ttc-SCW-aFky/images/icons/postgresql.svg?fit=max&auto=format&n=aLd-ttc-SCW-aFky&q=85&s=8bb2ac033d0a2ccbef51154a76e1e819" href="/guide/connections/postgresql" width="24" height="24" data-path="images/icons/postgresql.svg">
    Setup instructions for PostgreSQL databases
  </Card>
</CardGroup>
