> For the complete documentation index, see [llms.txt](https://docs.strongdm.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.strongdm.com/admin/resources/datasources/mongodb-replica-set.md).

# MongoDB (Replica Set)

## Overview

This guide describes how to add a MongoDB (Replica Set) database as a datasource in StrongDM.

When the resource is added, StrongDM proxies client connections through a [node](/admin/networking.md) (gateway, relay, or proxy cluster). This enables centralized access control, credential management, and audit logging.\
StrongDM supports MongoDB version 8 and under.

StrongDM supports two authentication modes for this resource type:

* **Username/password authentication**, using credentials stored in StrongDM or a Secret Store
* **AWS IAM authentication**, which uses the AWS identity of the StrongDM node (proxy worker, gateway, relay) instead of static credentials

StrongDM selects the authentication mode based on the resource configuration. If the **AWS Region** property is set, StrongDM authenticates with AWS IAM using the node's AWS identity, even if credentials are also configured. If **AWS Region** is blank, StrongDM authenticates with the configured username and password. If none of these properties are set, StrongDM will attempt to connect un-authenticated. To use IAM authentication, see [Set up IAM Authentication](#set-up-iam-authentication).

Use this guide to complete all necessary preparations to add this resource to your StrongDM environment; input the correct properties in the Admin UI, CLI, SDKs, or Terraform provider; and test for a successful connection.

For general information about how to add a database as a resource in StrongDM, see our main guide, [Add a Datasource](/admin/resources/datasources.md).

## Supported Versions and Clients

{% hint style="info" %}
StrongDM supports MongoDB versions 4.4, 5, 6, 7, and 8.
{% endhint %}

Clients supported include:

* Standard MongoDB drivers and libraries (for example, the official MongoDB client for Node.js, Python, Java, and so forth)
* Tools like `mongo` shell or GUI clients that support MongoDB replica set connection strings

## Prerequisites

To add your resource in StrongDM, you need to meet several technical and configuration prerequisites. Please ensure that the following requirements are met.

In StrongDM, you must have the following:

* Administrator permission level
* At least one operational StrongDM node (gateway, relay, or proxy cluster) that can reach the MongoDB replica set endpoint(s) over TCP (default port is `27017`)
* If using secrets management tools for storing your database credentials, a Secret Store configured in StrongDM

{% hint style="info" %}
To verify that the resource is accessible by the node, log in to the gateway or relay and use Netcat: `nc -zv <HOSTNAME> <PORT>` (in this example, `nc -zv testdb-01.fancy.org 3306`). If your gateway server can connect to this hostname, proceed.

Netcat is a tool for checking various hostnames and ports by either sending data (a ping) or checking for listeners on the ports. The command in the aforementioned example use "-z" to check for listeners without sending data and "-v" to show verbose output. If you don't have Netcat, you can install the Netcat package with whatever package manager you are using, such as "apt-get install netcat".
{% endhint %}

On the MongoDB side, you must have the following:

* Properly configured replica set, with the set name defined
* Database user with appropriate privileges (read or read/write, depending on your needs)
* Authentication database where the user is defined (commonly `admin`)
* TLS/SSL enabled, if required by your organization
* Network accessibility (firewalls, security groups, or VPC rules) that allows StrongDM nodes to connect

If using AWS IAM authentication, you must also have the following:

* MongoDB deployment that supports the `MONGODB-AWS` authentication mechanism, such as MongoDB Atlas (MongoDB 4.4 or later)
* StrongDM node running on AWS compute (for example, an EC2 instance) with an IAM role attached, or otherwise running with an AWS workload identity.
* MongoDB database user defined in the `$external` database whose username is the ARN of that IAM role

## Set up IAM Authentication

With AWS IAM authentication, the StrongDM node authenticates to MongoDB using its own AWS identity, so neither your users nor StrongDM stores static database credentials. Some setup is required in AWS and in MongoDB before adding the resource.

### Attach an IAM role to the node

Take this example where the StrongDM node is running in an AWS EC2 instance. Define the IAM role you wish to use, with a trust policy that allows EC2 to assume the role, as in the following example:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

Attach this role to the EC2 instance(s) running your StrongDM node. Every node that can proxy connections to this resource needs the role attached.

{% hint style="info" %}
The IAM role does not need any permission policies for MongoDB authentication itself. MongoDB verifies the node's identity with AWS STS; access is controlled by the database user you map to the role in the next step. Follow the principle of least privilege and attach only the policies your node otherwise requires.
{% endhint %}

### Map the IAM role to a MongoDB user

Create a database user in the `$external` database whose username is the ARN of the IAM role, and grant it the database roles your users need. For example, in `mongosh`:

```
use $external
db.createUser({
  user: "arn:aws:iam::123456789012:role/StrongDMGatewayRole",
  roles: [{ role: "readWrite", db: "myDatabase" }]
})
```

If you use MongoDB Atlas, instead add a database user with the **AWS IAM** authentication method and the IAM role ARN as the identity. See the [MongoDB AWS IAM authentication documentation](https://www.mongodb.com/docs/manual/core/security-aws-iam/) for details.

### Configure the resource for IAM

When you add the resource in StrongDM, set the **AWS Region** property to the region of the resource (for example, `us-west-2`) and leave **Username** and **Password** blank. Setting **AWS Region** is what enables IAM authentication for the resource.

{% hint style="warning" %}
If **AWS Region** is set, StrongDM uses IAM authentication even if a username and password are also configured. If neither **AWS Region** nor credentials are configured, StrongDM connects to the database without authenticating. There is no save-time validation of these combinations; a misconfigured resource (for example, a region set with no matching `$external` user) appears as an unhealthy datasource, and details are available on its **Diagnostics** tab.
{% endhint %}

## Resource Management in StrongDM

After all prerequisites and prep work is done, you are ready to add the resource to StrongDM. This section provides instructions for adding the resource in either the StrongDM Admin UI, CLI, Terraform provider, or SDKs.

{% tabs %}
{% tab title="Admin UI" %}
**Set up and Manage With the Admin UI**

If using the Admin UI to add MongoDB (replica set) as a resource to StrongDM, use the following steps.

1. Log in to the StrongDM Admin UI.
2. Go to **Resources** > **Managed Resources**.
3. Click **Add Resource**.
4. For **Resource Type**, select **MongoDB (replica set)**.
5. Complete all required [configuration properties](#configuration-properties) for your selected datasource type.
6. Click **Create** to save the resource.
7. Click the resource name to view status, diagnostic information, and setting details.
   {% endtab %}

{% tab title="CLI" %}
**Set up and Manage With the CLI**

This section provides an example of how to add the resource using the StrongDM CLI. For more information and examples, please see the [CLI Reference](/references/cli.md) documentation.

```
# Add MongoDB (Replica Set) datasource with username/password authentication
sdm admin datasources add mongodb-replicaset mongo-replica-prod
  --hostname="mongo-replica.example.org"
  --port=27017
  --username="mongo_user"
  --password="secret"
  --authentication-database="admin"
  --replica-set="rs0"
  --tls-required
  --bind-interface="127.0.0.1"
  --egress-filter="tag:env=prod"
  --proxy-cluster-id="n-1a2b345c67890123"
  --secret-store-id="se-e1b2"
  --subdomain="mongo-replica-prod"
  --tags="env=production,team=backend"
```

```
# Add MongoDB (Replica Set) datasource with IAM authentication
sdm admin datasources add mongodb-replicaset mongo-replica-prod
  --hostname="mongo-replica.example.org"
  --port=27017
  --region="us-west-2"
  --authentication-database="admin"
  --replica-set="rs0"
  --tls-required
  --bind-interface="127.0.0.1"
  --egress-filter="tag:env=prod"
  --proxy-cluster-id="n-1a2b345c67890123"
  --secret-store-id="se-e1b2"
  --subdomain="mongo-replica-prod"
  --tags="env=production,team=backend"
```

{% endtab %}

{% tab title="Terraform" %}
**Set up and Manage With Terraform**

This section provides an example of how to configure and manage the resource using the Terraform provider. For more information and examples, please see the [Terraform provider](https://github.com/strongdm/terraform-provider-sdm) documentation.

```
# Install StrongDM provider
terraform {
  required_providers {
    sdm = {
      source  = "strongdm/sdm"
      version = "16.5.0"
    }
  }
}

# Configure StrongDM provider
provider "sdm" {
  # Add API access key and secret key from Admin UI
  api_access_key = "njjSn...5hM"
  api_secret_key = "ziG...="
}

# Create MongoDB (Replica Set) resource with username/password authentication
resource "sdm_mongodb_replicaset" "mongo_replica_prod" {
  name                      = "mongo-replica-prod"
  hostname                  = "mongo-replica.example.org"
  port                      = 27017
  username                  = "mongo_user"
  password                  = "secret"
  authentication_database   = "admin"
  replica_set               = "rs0"
  tls_required              = true

  bind_interface            = "127.0.0.1"
  egress_filter             = "tag:env=prod"
  proxy_cluster_id          = "n-1a2b345c67890123"

  secret_store_id           = "se-e1b2"
  subdomain                 = "mongo-replica-prod"
  tags = {
    env   = "production"
    team  = "backend"
  }
}

# Create MongoDB (Replica Set) resource with IAM authentication
# Set region and omit username and password
resource "sdm_mongodb_replicaset" "mongo_replica_prod" {
  name                      = "mongo-replica-prod"
  hostname                  = "mongo-replica.example.org"
  port                      = 27017
  region                    = "us-west-2"
  authentication_database   = "admin"
  replica_set               = "rs0"
  tls_required              = true

  bind_interface            = "127.0.0.1"
  egress_filter             = "tag:env=prod"
  proxy_cluster_id          = "n-1a2b345c67890123"

  secret_store_id           = "se-e1b2"
  subdomain                 = "mongo-replica-prod"
  tags = {
    env   = "production"
    team  = "backend"
  }
}
```

{% endtab %}

{% tab title="SDKs" %}
**Set up and manage with SDKs**

In addition to the Admin UI, CLI, and Terraform, you may configure and manage your resource with any of the following SDK options: Go, Java, Python, and Ruby. Please see the following references for more information and examples.

| Language      | Reference                                                                | GitHub                                                                 | Examples                                                                        |
| ------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| Go            | [pkg.go.dev](https://pkg.go.dev/github.com/strongdm/strongdm-sdk-go/v17) | [strongdm-sdk-go](https://github.com/strongdm/strongdm-sdk-go)         | [Go SDK Examples](https://github.com/strongdm/strongdm-sdk-go-examples)         |
| Java          | [javadoc](https://strongdm.github.io/strongdm-sdk-java-docs/)            | [strongdm-sdk-java](https://github.com/strongdm/strongdm-sdk-java)     | [Java SDK Examples](https://github.com/strongdm/strongdm-sdk-java-examples)     |
| Python        | [pdocs](https://strongdm.github.io/strongdm-sdk-python-docs/)            | [strongdm-sdk-python](https://github.com/strongdm/strongdm-sdk-python) | [Python SDK Examples](https://github.com/strongdm/strongdm-sdk-python-examples) |
| Ruby          | [RubyDoc](https://www.rubydoc.info/gems/strongdm)                        | [strongdm-sdk-ruby](https://github.com/strongdm/strongdm-sdk-ruby)     | [Ruby SDK Examples](https://github.com/strongdm/strongdm-sdk-ruby-examples)     |
| {% endtab %}  |                                                                          |                                                                        |                                                                                 |
| {% endtabs %} |                                                                          |                                                                        |                                                                                 |

## **Configuration Properties**

The following configuration properties are required to define a MongoDB datasource in StrongDM. These settings control how StrongDM connects to the database, authenticates the connection, and optionally uses encryption or secret management. Each property must be correctly configured to ensure connectivity and access enforcement through StrongDM.

| Property                    | Requirement | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| --------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Display Name**            | Required    | Meaningful name to display the resource throughout StrongDM; exclude special characters like quotes (") or angle brackets (< or >)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| **Resource Type**           | Required    | Select **MongoDB (replica set)**. If you want to add a MongoDB resource without specifying a replica set, see the instructions for [MongoDB (single host)](/admin/resources/datasources/mongodb-single-host.md) resource type instead.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| **Proxy Cluster**           | Required    | Defaults to "None (use gateways)"; if using [proxy clusters](/admin/networking/proxy-clusters.md), select the appropriate cluster to proxy traffic to this resource                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| **Hostname**                | Required    | Hostname for your MongoDB database resource; [must be accessible](#prerequisites) to a gateway or relay                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| **Port**                    | Required    | Port to use when connecting to your MongoDB database; default port value is **27017**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| **Connectivity Mode**       | Required    | Select either **Virtual Networking Mode**, which lets users connect to the resource with a software-defined, IP-based network; or **Loopback Mode**, which allows users to connect to the resource using the local loopback adapter in their operating system; this field is shown if [Virtual Networking Mode](/admin/clients/client-networking/virtual-networking-mode.md) enabled for your organization                                                                                                                                                                                                                                                                                                                                       |
| **IP Address**              | Optional    | If **Virtual Networking Mode** is the selected connectivity mode, an IP address value in the configured Virtual Networking Mode subnet in the organization network settings; if **Loopback Mode** is the selected connectivity mode, an IP address value in the configured Loopback IP range in the organization network settings (by default, `127.0.0.1`); if not specified, an available IP address in the configured IP address space for the selected connectivity mode will be automatically assigned; this field is shown if [Virtual Networking Mode](/admin/clients/client-networking/virtual-networking-mode.md) and/or [multi-loopback mode](/admin/clients/client-networking/loopback-ip-ranges.md) is enabled for your organization |
| **Port Override**           | Optional    | If **Virtual Networking Mode** is the selected connectivity mode, a port value between 1 and 65535 that is not already in use by another resource with the same IP address; if **Loopback Mode** is the selected connectivity mode, a port value between 1024 to 64999 that is not already in use by another resource with the same IP address; when left empty with Virtual Networking Mode, the system assigns the default port to this resource; when left empty for Loopback Mode, an available port that is not already in use by another resource is assigned; preferred port also can be modified later from the [Port Overrides settings](/admin/resources/port-overrides.md)                                                            |
| **DNS**                     | Optional    | If Virtual Networking Mode is the selected connectivity mode, a unique hostname alias for this resource; when set, causes the desktop app to display this resource's human-readable DNS name (for example, `k8s.my-organization-name`) instead of the bind address that includes IP address and port (for example, `100.64.100.100:5432`)                                                                                                                                                                                                                                                                                                                                                                                                        |
| **AWS Region**              | Optional    | Set if using IAM authentication; AWS region of the resource (for example, `us-west-2`); set to authenticate with AWS IAM using the node's identity, and leave **Username** and **Password** blank; when **AWS Region** is set, StrongDM uses IAM authentication even if credentials are also configured; see [Set up IAM Authentication](#set-up-iam-authentication)                                                                                                                                                                                                                                                                                                                                                                             |
| **Authentication Database** | Required    | Enter the name of the authentication database (that is, the database that MongoDB users authenticate against, *not* the database to which you are granting access); in this example, the authentication database is `sdmdb`, while the MongoDB default database is `admin`                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| **Secret Store**            | Optional    | Credential store location; defaults to none (credentials are stored in StrongDM resource configuration); learn more about [Secret Store](#secret-store-options) options                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| **Username**                | Optional    | Username to utilize when connecting to this datasource; displays when Secret Store integration is not configured for your organization or when StrongDM serves as the secret store; Required for username/password authentication                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| **Password**                | Optional    | Password for the user connecting to this datasource; displays when Secret Store integration is not configured for your organization or when StrongDM serves as the secret store; Required for username/password authentication                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| **Username (path)**         | Required    | Path to the secret in your Secret Store location (for example, `path/to/credential?key=optionalKeyName` where key argument is optional); required when using a non-StrongDM Secret Store type for username/password authentication                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| **Password (path)**         | Required    | Path to the secret in your Secret Store location (for example, `path/to/credential?key=optionalKeyName` where key argument is optional); required when using a non-StrongDM Secret Store type for username/password authentication                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| **Replica Set**             | Optional    | The name of the MongoDB replica set, which can be found in the Web UI or your shard prefix                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| **TLS Required**            | Optional    | Indicator to require StrongDM to use TLS to connect to the database                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| **Connect to Replica?**     | Optional    | Select this option if you would like StrongDM to connect to a secondary (read-only) replica instead of the primary node.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **Resource Tags**           | Optional    | Datasource [Tags](/references/cli/tags.md) consisting of key-value pairs `<KEY>=<VALUE>` (for example, `env=dev`)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |

### Secret Store options

By default, datasource credentials are stored in StrongDM. However, these credentials can also be saved in a secrets management tool.

Non-StrongDM options appear in the **Secret Store** dropdown if they are created under **Network** > **Secret Stores**. When you select another Secret Store type, its unique properties display. For more details, see [Configure Secret Store Integrations](/admin/access/secret-stores.md).

### Resource status

After a resource is created, the Admin UI displays that resource as unhealthy until the healthchecks run successfully. When the resource is ready, the **Health** icon indicates a positive, green status.

When the resource does not display a positive status, click the resource name to go to the **Diagnostics** tab and check for errors.

## Test the Connection

After you have added your resource in StrongDM, follow these steps to verify that it’s working correctly.

1. Assign yourself access by ensuring that your user or role has access to the resource. In the StrongDM Admin UI, go to **Access** > **Roles**, and verify that the resource is attached to a role you’re in.
2. In the CLI, run `sdm status` to list the available datasources. Ensure that the resource appears in your list of accessible datasources.
3. Start a session to the resource, as in the following example:

   ```bash
   sdm connect mongo-replica-prod
   ```
4. Connect using a MongoDB client (for example, `mongo` shell or another client), specifying the hostname, port, username, password, replica set name, and authentication database. For example:

   ```
   mongo --host localhost:<PORT> --username $USERNAME --password $PASSWORD --authenticationDatabase admin --replicaSet rs0
   ```

   <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><p>If the resource uses AWS IAM authentication, no username or password is needed; the StrongDM node authenticates on your behalf.</p></div>
5. Run a run a test command. For example:

   ```
   db.adminCommand({ping: 1})
   ```
6. In the StrongDM Admin UI, check **Logs > Queries** (and **Logs > Connections**) to verify that your session and operations were logged.

When these steps succeed, you’re ready to connect to your resource through StrongDM.

## Client Connections

Due to the way MongoDB manages connections, when a user connects to a MongoDB resource via StrongDM, the specific node in the cluster that they are connected to may vary. Considerations such as whether that node is read-only are ignored, and the user will be connected to any node that's available in the cluster.

### Help

If you still encounter issues, please consult the [StrongDM Help Center](https://help.strongdm.com/hc/en-us).

Be prepared to provide the following information to StrongDM Support, so that they can inspect logs and confirm node and resource health:

* Resource name or ID
* CLI error output or logs
* Node name and region


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.strongdm.com/admin/resources/datasources/mongodb-replica-set.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
