> ## Documentation Index
> Fetch the complete documentation index at: https://ngquct-feat-cloudflare-r2-sql.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# MongoDB

> Connect to MongoDB with MQL shell queries, collection browsing, and automatic Atlas SRV setup

Collections appear as tables in the sidebar. Documents display with top-level fields as columns and nested objects as formatted JSON.

MongoDB is a registry plugin. Picking it in the **Choose a Database** sheet prompts to install; connecting to a saved MongoDB connection installs it without asking. You can also install **MongoDB Driver** from **Settings > Plugins > Browse**.

## Quick Setup

<Steps>
  <Step title="Create Connection">
    Click **New Connection**, select **MongoDB**, enter hosts and credentials, and click **Create**
  </Step>

  <Step title="Test Connection">
    Click **Test Connection** to verify
  </Step>
</Steps>

## Connection Settings

| Field              | Default           | Notes                                                                        |
| ------------------ | ----------------- | ---------------------------------------------------------------------------- |
| **Hosts**          | `localhost:27017` | Add multiple `host:port` pairs for replica sets                              |
| **Username**       | -                 | Leave empty for local dev without auth                                       |
| **Password**       | -                 |                                                                              |
| **Auth Mechanism** | Default           | SCRAM-SHA-1, SCRAM-SHA-256, X.509, or AWS IAM. In the Authentication section |

The form has no Database field. On connect TablePro opens the first non-system database it finds, and **Cmd+K** switches to another. A database in a connection URL path (`mongodb://host:27017/mydb`) is used instead.

**Advanced**: **Auth Database** (usually `admin`), **Read Preference**, **Write Concern**, **Use SRV Record**, and **Replica Set** name.

Leaving **Auth Database** empty authenticates against the database in the connection URL path, or `admin` when there is none. Switching databases in the app never changes it, so browsing a database your user has no account in does not break the connection.

<Frame caption="MongoDB connection form">
  <img className="block dark:hidden" src="https://mintcdn.com/ngquct-feat-cloudflare-r2-sql/wtMckuN2hfshdEnb/images/mongodb-connection-form.png?fit=max&auto=format&n=wtMckuN2hfshdEnb&q=85&s=be809403538552bb38de50b6ba94166c" alt="MongoDB connection form with the multi-host Hosts editor" width="1560" height="960" data-path="images/mongodb-connection-form.png" />

  <img className="hidden dark:block" src="https://mintcdn.com/ngquct-feat-cloudflare-r2-sql/wtMckuN2hfshdEnb/images/mongodb-connection-form-dark.png?fit=max&auto=format&n=wtMckuN2hfshdEnb&q=85&s=af6f788b40da009e34fef2775c8d28a7" alt="MongoDB connection form with the multi-host Hosts editor" width="1560" height="960" data-path="images/mongodb-connection-form-dark.png" />
</Frame>

## MongoDB Atlas (SRV)

The **Use SRV Record** toggle in Advanced connects with the `mongodb+srv://` scheme. For hosts ending in `.mongodb.net`, TablePro enables SRV automatically and turns TLS on if the SSL mode is Disabled, since Atlas requires both. An Atlas connection needs only the cluster hostname, username, and password.

## Replica Sets

The **Hosts** field accepts multiple `host:port` pairs separated by commas (for example `host1:27017,host2:27017,host3:27017`). TablePro discovers the primary automatically and routes writes there. Set the replica set name in **Advanced**.

You can also paste a multi-host URI directly:

```text theme={null}
mongodb://user:pass@host1:27017,host2:27017,host3:27017/db?replicaSet=rs0
```

<Note>
  Over an SSH tunnel TablePro connects to the first host only and drops the rest of the list. Replica set discovery and failover are off for that session.
</Note>

## SSL/TLS

The MongoDB driver has no TLS fallback. **Preferred** behaves the same as **Required** (the SSL pane shows a warning). For unencrypted local instances, use **Disabled** or [SSH tunneling](/databases/ssh-tunneling). See [SSL/TLS](/features/ssl) for details.

## Connection URL

```text theme={null}
mongodb://user:password@host:27017/database?authSource=admin
mongodb+srv://user:password@cluster.mongodb.net/database
```

The `mongodb+srv://` scheme resolves hosts through DNS SRV records and does not allow a port. If you paste an SRV URL that includes one (for example `cluster.mongodb.net:27017`), TablePro strips it before connecting. The plain `mongodb://` scheme keeps any port you provide.

See [Connection URL Reference](/databases/connection-urls) for all parameters.

## Features

**Collection Browsing**: Sidebar shows all collections. Click to view documents in the data grid. Top-level fields render as columns, nested objects and arrays as formatted JSON, ObjectIds as strings. The grid schema is inferred by sampling documents.

**New Database**: The dialog asks for a database name and the name of its first collection. Both are required. MongoDB stores a database only once it holds a collection, so a name on its own would disappear as soon as the sidebar refreshed. The collection is created empty.

**Views**: **New View** in the sidebar opens a query tab with a `db.createView("view_name", "source_collection", [pipeline])` template. Editing a view definition pre-fills a `db.runCommand({"collMod": ...})` command.

**Explain**: Press `Cmd+Option+E` on an MQL statement. TablePro converts `find`, `aggregate`, `countDocuments`, update, delete, and `findOneAnd*` calls into `db.runCommand({"explain": ..., "verbosity": "executionStats"})`.

**MQL Shell Queries**: Filters and pipelines are parsed as JSON and Extended JSON, not JavaScript. Quote every key, operators included: `{age: {$gte: 18}}` fails with a parse error. mongosh helpers like `ISODate("2025-01-01")` fail too; write `{"$date": "2025-01-01T00:00:00Z"}`. The editor has no comment syntax, so a `//` line becomes part of the statement.

Find with a filter:

```javascript theme={null}
db.users.find({"age": {"$gte": 18}, "active": true})
```

Find with a projection and a sort:

```javascript theme={null}
db.orders.find(
  {"status": "completed"},
  {"customerId": 1, "total": 1, "date": 1}
).sort({"date": -1}).limit(20)
```

Aggregation pipeline, with dates in Extended JSON:

```javascript theme={null}
db.sales.aggregate([
  {"$match": {"date": {"$gte": {"$date": "2025-01-01T00:00:00Z"}}}},
  {"$group": {"_id": "$product", "totalSales": {"$sum": "$amount"}}},
  {"$sort": {"totalSales": -1}},
  {"$limit": 10}
])
```

Count documents:

```javascript theme={null}
db.users.countDocuments({"role": "admin"})
```

**Collection references**: Write `db.users`, `db["users"]`, or `db.getCollection("users")`. The bracket and `getCollection` forms take the name exactly as written, so use them for names that contain dots or spaces, start with a digit, or match a database method such as `stats` or `version`. Single quotes and backticks work in place of double quotes. `db.getSiblingDB(...)` is not supported: a query always runs against the database the connection is using.

**Supported methods**: collection-level `find`, `findOne`, `aggregate`, `countDocuments`/`count`, `insertOne`/`insertMany`, `updateOne`/`updateMany`, `replaceOne`, `deleteOne`/`deleteMany`, `findOneAndUpdate`/`findOneAndReplace`/`findOneAndDelete`, `createIndex`, `dropIndex`, `drop`; database-level `getCollectionNames`/`listCollections`, `createCollection`, `dropDatabase`, `version`, `stats`. Anything else goes through `db.runCommand({...})` or `db.adminCommand({...})`. Unlisted shell methods (for example `distinct` or `getUsers`) return an unsupported-method error.

## Troubleshooting

**Connection refused**: Check MongoDB is running (`brew services start mongodb-community`), verify host/port in `mongod.conf`, check `bindIp` setting.

**Auth failed**: The error names the database TablePro authenticated against. If that is not where your user lives, set **Auth Database** in the Advanced section. Otherwise verify username, password, and auth mechanism. The MQL editor does not parse `db.getUsers()` or `db.createUser()`; inspect users with `db.runCommand({"usersInfo": 1})` or manage them in mongosh.

**Timeout**: Verify host/port, check network and firewall, whitelist your IP in MongoDB Atlas.

**A collection is slow to open**: A sort or a filter on a field with no index makes MongoDB read every document, even when you only ask for 20 rows, because it has to look at all of them to find which 20 come first. Check the Structure tab for an index on the field you sorted or filtered by, and add one if it is missing. `Cmd+.` stops the query on the server.

**The row total shows `~`**: That is an estimate read from collection metadata, which is instant. TablePro caps the automatic count at 5 seconds and keeps the estimate if the server takes longer, so browsing is never held up by counting. **Count exactly** runs a real count with your configured query timeout. Views and time-series collections have no metadata count, so their estimate can be missing.

## Limitations

* Transactions are not exposed. Statements always run standalone, on any topology.
* The grid schema is inferred by sampling documents, not read from a validator.
* GridFS buckets are not browsable.
* Change streams are unsupported.
