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

# MongoDB

> Connect to MongoDB 5.0+ with MQL shell queries, collection browsing, and BSON type display

# MongoDB Connections

TablePro supports MongoDB 5.0 and later. Collections appear as tables in the sidebar. Documents display with fields as columns, and nested objects render as formatted JSON.

## Quick Setup

<Steps>
  <Step title="Create Connection">
    Click **New Connection**, select **MongoDB**, enter host/port/username/password/database, 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 hosts for replica sets                                  |
| **Database**      | -                 | Optional. Leave empty to browse all databases. Switch with **Cmd+K** |
| **Username**      | -                 | Leave empty for local dev without auth                               |
| **Password**      | -                 |                                                                      |
| **Auth Database** | `admin`           | Database to authenticate against                                     |

**Advanced** (Optional): Configure **Read Preference** (primary, secondary, nearest) and **Write Concern** (majority for stronger durability) for replica sets.

<Frame caption="MongoDB connection form">
  <img className="block dark:hidden" src="https://mintlify.s3.us-west-1.amazonaws.com/ngquct-worktree-statusbar-redesign/images/mongodb-connection-form.png" alt="MongoDB connection form" />

  <img className="hidden dark:block" src="https://mintlify.s3.us-west-1.amazonaws.com/ngquct-worktree-statusbar-redesign/images/mongodb-connection-form-dark.png" alt="MongoDB connection form" />
</Frame>

## 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 the **Advanced** tab.

You can also paste a multi-host URI directly:

```
mongodb://user:pass@host1:27017,host2:27017,host3:27017/db?replicaSet=rs0
```

<Note>
  SSH tunneling only forwards the first host. Other members must be reachable from the SSH server.
</Note>

## Example Configurations

**Local**: host `localhost:27017`, no auth, database `myapp`
**Docker**: host `localhost:27017` (or mapped port), password from `MONGO_INITDB_ROOT_PASSWORD` env, auth DB `admin`
**MongoDB Atlas**: Enable SSL/TLS in connection form
**Remote**: Use [SSH tunneling](/databases/ssh-tunneling) for secure access

## SSL/TLS

The MongoDB driver has no TLS fallback. **Preferred** behaves the same as **Required** (the SSL pane shows a warning). MongoDB Atlas requires TLS, so use **Required** or **Verify CA**. 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 data grid.

**Document Viewing**: Top-level fields as columns, nested objects as formatted JSON, arrays as JSON arrays, ObjectIds as strings, BSON types formatted appropriately. Schema inferred by sampling.

**Collection Duplication**: Open **Create Table**, click **Duplicate**, select source collection. Uses `aggregate` with `$out`, recreates indexes. Result named `originalName_copy`.

**MongoDB Shell Queries** (MQL syntax):

```javascript theme={null}
// Find documents with filtering
db.users.find({ age: { $gte: 18 }, active: true })

// Find with projection and sorting
db.orders.find(
  { status: "completed" },
  { customerId: 1, total: 1, date: 1 }
).sort({ date: -1 }).limit(20)

// Aggregation pipeline
db.sales.aggregate([
  { $match: { date: { $gte: ISODate("2025-01-01") } } },
  { $group: { _id: "$product", totalSales: { $sum: "$amount" } } },
  { $sort: { totalSales: -1 } },
  { $limit: 10 }
])

// Count documents
db.users.countDocuments({ role: "admin" })

// Distinct values
db.products.distinct("category")
```

**CRUD**: Insert with `insertOne()`/`insertMany()`, update with `updateOne()`/`updateMany()`, delete with `deleteOne()`/`deleteMany()`.

## Troubleshooting

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

**Auth failed**: Verify username/password/auth database. Check user roles with `db.getUsers();` Create user with `db.createUser({user:"appuser", pwd:"password", roles:[{role:"readWrite", db:"myapp"}]})`

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

**Limitations**: Transactions need replica set/sharded cluster, schema inferred by sampling, capped collections restricted, GridFS not browsable, change streams unsupported.

**Performance**: Use filters, `limit()`, pagination, indexes. Analyze with `explain("executionStats")`.
