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

# MongoDB

> How to connect to a MongoDB Resource using the Formal Connector

## Requirements

### Networking

Certain ports must be accessible to connect to Formal Resources. You can listen on multiple ports simultaneously for various Resources.

For accessing MongoDB, you may assign any port except 8080 (Connector's health check port). Ensure your security groups are configured to allow traffic on the designated port.

### Database health check

Formal periodically assesses the health of the database. We test the connection to the `admin` database (`authSource` and `defaultauthdb` [are not specified by default in our generated URI](https://www.mongodb.com/docs/manual/reference/connection-string/)).

## SRV connection strings

MongoDB clusters can be published as a single DNS name whose SRV records point to the actual hostnames of the cluster's servers. That DNS name is what `mongodb+srv://` connection strings contain, such as the ones MongoDB Atlas provides.

Set the Resource's `hostname` to it, without the scheme (e.g. `cluster0.abcde.mongodb.net`). The Connector notices the SRV records, looks them up, and connects to the server accepting writes, so nothing needs changing when the cluster fails over.

> [!NOTE]
>
> The Resource's `port` is ignored for these Resources, because each SRV record carries the port of the server it points to.

## Replica sets

Formal supports MongoDB replica sets when clients connect to the Connector over TLS (`tls=true`). Replica set members advertise their own addresses to clients. The Connector rewrites those addresses to Connector hostnames and routes each connection to the right member using SNI, so drivers discover the replica set, follow failovers, and honor `readPreference` while every connection stays on the Connector.

> [!NOTE]
>
> This requires `*.<host>` DNS entries pointing at the Connector, and a Connector certificate covering them.

Clients connecting without TLS are pinned to a single member, and need `directConnection=true` to keep their driver from looking for the other members. Their reads go to that member whatever their `readPreference`.

## Connect to MongoDB

> [!WARNING]
>
> When a session-level policy denies by default, some clients such as `mongosh` cannot establish a connection, because they open unauthenticated connections before authentication.
>
> To connect under such a policy, use the [Formal Endpoint](https://docs.formal.ai/docs/guides/client-apps/desktop-app.md), which is not affected by this.

### mongosh

To connect using `mongosh`, execute the following command:

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
mongosh --host CONNECTOR_HOSTNAME:PORT -u 'idp:formal:human:john@joinformal.com'
```

You can also specify a MongoDB URI directly:

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
mongosh 'mongodb://CONNECTOR_HOSTNAME:PORT/' -u 'FORMAL_USERNAME'
```

Make sure to replace `CONNECTOR_HOSTNAME`, `PORT`, `DATABASE_NAME`, and
`FORMAL_USERNAME` with the right values. To map Formal identities to upstream
credentials, see
[Select a default Native User](https://docs.formal.ai/docs/guides/core-concepts/resources/native-users.md#select-a-default-native-user).

> [!NOTE]
>
> You can access your Formal Credentials in the [Control Plane](https://app.formal.ai).

> [!NOTE]
>
> You are free to use any preferred client.

## Smart Routing

The Connector features Smart Routing for MongoDB, allowing the linkage of an unlimited number of Resources over the same port (e.g. 27017).

Set the connection string's `appName` option to `formal_resource_name=RESOURCE_NAME`. The Connector reads the resource name from `appName`, not from the database name:

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
mongosh 'mongodb://CONNECTOR_HOSTNAME:PORT/?appName=formal_resource_name=RESOURCE_NAME'
```

## Data Discovery

The [Data Discovery Satellite](https://docs.formal.ai/docs/guides/core-concepts/satellites.md#data-discovery-satellite) catalogs MongoDB into the [data inventory](https://docs.formal.ai/docs/guides/core-concepts/data-inventory.md). Databases are listed as databases, collections as tables, and MongoDB views as views. MongoDB has no schema layer, so paths have the `DATABASE.COLLECTION.FIELD` shape, matching the paths policies target.

MongoDB does not keep a catalog of the fields a collection holds, so discovery reads the first 500 documents of each collection and reports the union of the fields it finds:

* Top-level fields become columns, with the BSON type MongoDB's `$type` operator reports. A field whose type differs between documents is reported as `mixed`.
* Fields inside embedded documents become sub-columns. Array indexes are left out of the path, so a field of the documents inside an array will be reported once, at `DATABASE.COLLECTION.ARRAY.FIELD`.
* An array of scalars is a single column: its values are sampled at the array's own path, which is also where policies mask them.

Fields that only appear in documents beyond the first 500 of a collection are not discovered.

The native user configured for discovery needs `listDatabases` on the cluster, plus `listCollections` and `find` on every database to catalog. The built-in `readAnyDatabase` role covers all three. Without `listDatabases`, MongoDB returns only the databases the native user holds privileges on, and discovery catalogs those.

The `admin`, `config`, and `local` databases are listed but not descended into.

## Policy Evaluation

Formal supports the following policy evaluation stages for MongoDB:

* **Session**: Evaluate and enforce policies at connection time
* **Request**: Evaluate and enforce policies on a command before it reaches the database, through `input.mongodb` and `input.table_paths`
* **Response**: Evaluate and enforce policies after data retrieval

### Multiple Connector instances

When a response policy (e.g., masking) applies, the Connector must retain the original query to correctly trace fields on subsequent cursor data fetches. Because of this, it can't enforce the policy on a cursor it didn't open, and thus blocks these data fetches.

To avoid queries failing partway through their results when running several Connector instances behind a load balancer, keep each client on a single instance with source IP stickiness.

* **Kubernetes:** set `sessionAffinity: ClientIP` on the Connector Service. For a `LoadBalancer` or `NodePort` Service, also set `externalTrafficPolicy: Local` so the Service sees the client's IP.
* **AWS Network Load Balancer:** enable stickiness of type `source_ip` on the Connector target group.


## Related topics

- [Smart Routing](https://docs.formal.ai/docs/guides/core-concepts/resources/smart-routing.md)
- [Policy Evaluation](https://docs.formal.ai/docs/guides/policies/evaluation.md)
- [Connector](https://docs.formal.ai/docs/changelog/connector.md)
- [Formal Endpoint](https://docs.formal.ai/docs/changelog/endpoint.md)
- [Data Discovery](https://docs.formal.ai/docs/changelog/data-discovery.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.