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

# MongoDB

> Connect to MongoDB and run mongosh JavaScript, browse collections, and set up Atlas SRV automatically

export const name_0 = "MongoDB"

export const plugin_0 = "MongoDB Driver"

The query tab is a JavaScript shell. Write `db.orders.find({status: "new"})` the way mongosh takes it, unquoted keys and all, and keep going into variables, loops and `forEach`. Collections appear as tables in the sidebar, with top-level fields as columns and nested objects as formatted JSON.

The {name_0} driver is not in the app. Picking {name_0} in the **Choose a Database** sheet offers the
download before the form opens, and opening a saved {name_0} connection installs it without asking.
**Settings > Plugins > Browse > {plugin_0}** installs it up front. See [Plugins](/features/plugins).

## Quick setup

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

  <Step title="Test Connection">
    Click **Test Connection** to verify, then **Save & Connect**
  </Step>
</Steps>

## Connection settings

| Field              | Default           | Notes                                                                |
| ------------------ | ----------------- | -------------------------------------------------------------------- |
| **Hosts**          | `localhost:27017` | Several `host:port` pairs for a replica set                          |
| **Username**       | -                 | Leave empty for local dev without auth                               |
| **Password**       | -                 |                                                                      |
| **Database**       | -                 | Opens straight into that database. Leave it empty to browse them all |
| **Auth Database**  | -                 | Advanced. Where your user account lives, usually `admin`             |
| **Auth Mechanism** | Default           | SCRAM-SHA-1, SCRAM-SHA-256, X.509, or AWS IAM, under Authentication  |

Naming a **Database** skips listing every database on the server, which is worth doing on a cluster with hundreds. Leave it empty and the first non-system database opens instead. `Cmd+K` switches either way, on the same connection, with no reconnect.

**Auth Database** is a separate question: it says where your account is defined, not what you browse. Left empty, it follows the **Database** field. An account defined in `admin` needs **Auth Database** set to `admin` whenever **Database** names something else, or authentication fails. SRV connections authenticate against `admin` regardless, unless told otherwise. Switching databases in the app never changes it, so browsing a database your user has no account in is fine.

Also in Advanced: **Read Preference**, **Write Concern**, **Use SRV Record**, **Replica Set** name, and **Legacy UUID Encoding**. There is no minimum server version; the driver adapts what it asks for to what the server answers.

<Frame caption="MongoDB connection form">
  <img className="block dark:hidden" src="https://mintcdn.com/ngquct-feat-mongodb-edit-document/JYz1jNQLM-AYDjM9/images/mongodb-connection-form.png?fit=max&auto=format&n=JYz1jNQLM-AYDjM9&q=85&s=2d13ae4b1a72bac668212ccba8ee80dd" 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-mongodb-edit-document/JYz1jNQLM-AYDjM9/images/mongodb-connection-form-dark.png?fit=max&auto=format&n=JYz1jNQLM-AYDjM9&q=85&s=c9b37b42d57bbf07ad6273b102d96a8f" alt="MongoDB connection form with the multi-host Hosts editor" width="1560" height="960" data-path="images/mongodb-connection-form-dark.png" />
</Frame>

On MongoDB 4.0 and later the database list is requested as authorized databases only, so an account without the `listDatabases` privilege still sees what it can read. On an older server that list comes back empty: name a **Database** on the connection instead.

## Connection URL

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

`mongodb+srv://` resolves hosts through DNS SRV records and takes no port; one pasted into the field is stripped before connecting. Plain `mongodb://` keeps whatever port you give it. See [Connection URL Reference](/connections/urls).

## MongoDB Atlas (SRV)

An Atlas connection needs the cluster hostname, a username, and a password. Atlas requires SRV and TLS, so a host ending in `.mongodb.net` gets both turned on for you, TLS only if the SSL mode was still Disabled. Elsewhere the **Use SRV Record** toggle in Advanced does the same job. Add your current IP to the cluster's access list in the Atlas console first: traffic from an address that is not on it times out rather than failing.

## Replica sets

The **Hosts** field takes comma-separated pairs (`host1:27017,host2:27017,host3:27017`), the primary is discovered, and writes are routed to it. Set the replica set name in Advanced. A multi-host URI pastes in directly:

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

<Warning>
  <Warning>
    Over an SSH tunnel only the first host is used and the rest of the list is dropped. Replica set discovery and failover are off for that session, with nothing on screen to say so.
  </Warning>
</Warning>

## Browsing collections

Click a collection to page through its documents. The columns are the fields in the documents on screen, then any field the collection's `$jsonSchema` validator declares that none of them hold, so an empty collection still shows the fields it was created with. ObjectIds render as strings, arrays and nested objects as formatted JSON.

An edited cell keeps its field's type. A date stays a date, whether typed as `2024-01-02T03:04:05Z`, as `2024-01-02`, or picked in the date picker, which writes your local time. An ObjectId stays an ObjectId, an integer past 2^53 is sent as a 64-bit integer, and a field the validator declares as `string` is written as text even when it reads `123` or `true`. Where the grid has no type to go on, `123` is a number and `{"a": 1}` a document; text that only looks like JSON is written as a string.

The filter bar's column picker lists paths inside nested objects and arrays of objects, so `customer.country` and `items.sku` filter directly; a row on an array field chooses **any element** or **same element**, which makes one array entry satisfy every row set to it. See [Filtering](/features/filtering#nested-fields). A field name containing a literal dot is left out of the picker, since MongoDB reads a dot as a path separator; reach it with `$getField` inside `$expr`.

The Structure tab lists a collection's indexes; drop one from a query tab with `db.users.dropIndex("email_1")`. **New Database** asks for a database name and a first collection, both required. **New View** opens a query tab holding a `db.createView("view_name", "source_collection", [pipeline])` template, and editing a view pre-fills `db.runCommand({"collMod": …})`.

### Binary UUIDs

A binary subtype 4 field renders as `UUID("8cd003eb-4a25-4324-9332-88fce2da0d1a")`. Subtype 3 is the legacy format, and its bytes do not say which driver wrote them, so it stays `BinData(3, "…")` until **Legacy UUID Encoding** on the connection is set to Java, C#, or Python. Match it to the driver that wrote the data: the wrong choice shows a valid-looking but wrong UUID.

Once set, the value renders as `LegacyJavaUUID("…")` and reads that way everywhere, filters and MQL export included. Nothing stored is rewritten, `uuidRepresentation=javaLegacy` in a pasted URL sets the same option, and a change takes effect on the next connect.

## Creating a collection

Choose **Database > New Table…**. Each row of the grid is a field, and its type is one of the BSON types in the list: `objectId`, `string`, `int`, `long`, `double`, `decimal`, `date`, `bool`, `array`, `object` and the rest. **Create Table** turns the rows into a `$jsonSchema` validator and runs `db.createCollection("articles", {"validator": …})`, which **SQL Preview** shows first.

<Frame caption="Nullable fields also accept null; NOT NULL ones go in required">
  <img className="block dark:hidden" src="https://mintcdn.com/ngquct-feat-mongodb-edit-document/JYz1jNQLM-AYDjM9/images/mongodb-create-collection.png?fit=max&auto=format&n=JYz1jNQLM-AYDjM9&q=85&s=2d5a7461df491adc3598c70ae732e896" alt="SQL Preview tab of Create Table showing db.createCollection for articles with a $jsonSchema listing _id, title, tags, date and schemaVersion" width="1560" height="960" data-path="images/mongodb-create-collection.png" />

  <img className="hidden dark:block" src="https://mintcdn.com/ngquct-feat-mongodb-edit-document/JYz1jNQLM-AYDjM9/images/mongodb-create-collection-dark.png?fit=max&auto=format&n=JYz1jNQLM-AYDjM9&q=85&s=89f5ce34bd837d1e5eb44b2dac987120" alt="SQL Preview tab of Create Table showing db.createCollection for articles with a $jsonSchema listing _id, title, tags, date and schemaVersion" width="1560" height="960" data-path="images/mongodb-create-collection-dark.png" />
</Frame>

| Row                  | Becomes                                                                       |
| -------------------- | ----------------------------------------------------------------------------- |
| **Nullable** NO      | The field is in `required`: a document without it, or with `null`, is refused |
| **Nullable** YES     | The field is optional and may hold `null`                                     |
| `_id`                | Always the key, typed `objectId`. Leave it out and MongoDB still adds one     |
| No rows, only a name | A collection with no validator                                                |

MongoDB enforces the validator with its defaults, `strict` and `error`, so an insert or edit of the wrong type fails with `Document failed validation`. **Primary Key** on any field other than `_id` is refused, and so are field names that start with `$` or contain a dot.

Each row on the **Indexes** tab runs as a `createIndex` after the collection is made, with its fields in the order listed. **BTREE** is an ascending key, **HASH** is `hashed`, **FULLTEXT** is `text`, and **SPATIAL** is `2dsphere`. A hashed index takes one field and cannot be unique, and a text index cannot be unique either.

## Inserting documents

A field exists only in the documents that hold it, so a collection with no documents and no validator shows `_id` alone and has no column to type a field into. Choose **Edit > Insert Document…** to write a whole document instead. It is on a row's context menu too, and on the context menu of an empty grid.

<Frame caption="The first document of an empty collection">
  <img className="block dark:hidden" src="https://mintcdn.com/ngquct-feat-mongodb-edit-document/JYz1jNQLM-AYDjM9/images/mongodb-insert-document.png?fit=max&auto=format&n=JYz1jNQLM-AYDjM9&q=85&s=2c43b193d62315a9f5e185ea907fdd87" alt="Insert Document sheet over the empty events collection, holding a document with a name, a channel, a date, a count and a list of tags" width="3024" height="1722" data-path="images/mongodb-insert-document.png" />

  <img className="hidden dark:block" src="https://mintcdn.com/ngquct-feat-mongodb-edit-document/JYz1jNQLM-AYDjM9/images/mongodb-insert-document-dark.png?fit=max&auto=format&n=JYz1jNQLM-AYDjM9&q=85&s=c8d6588222133ff249e12baab3e994a1" alt="Insert Document sheet over the empty events collection, holding a document with a name, a channel, a date, a count and a list of tags" width="3024" height="1722" data-path="images/mongodb-insert-document-dark.png" />
</Frame>

The text is Extended JSON: quote every field name, and write an ObjectId as `{"$oid": "…"}`, a date as `{"$date": "2024-05-01T10:00:00Z"}` and a decimal as `{"$numberDecimal": "1.10"}`. A whole number is stored as a 32-bit integer, or as a 64-bit one when it does not fit; `{"$numberLong": "5"}` stores a small 64-bit integer. A number with a decimal point is a double. Fields are stored in the order written. Leave out `_id` and the server generates one.

## Editing documents

A cell edits one value. To add, rename or remove a field, select one row and choose **Edit > Edit Document…**, or choose **Edit Document…** on the row's context menu. It works on a collection tab with no unsaved grid edits, not on a query tab.

The sheet reads the document from the server again, so it shows what is stored now rather than what the grid loaded. A value reads as plain JSON when that stores the same type, and keeps its wrapper when it would not: a 64-bit integer small enough for 32 bits stays `{"$numberLong": "5"}`, and a date before 1970 or after 9999 stays `{"$date": {"$numberLong": "…"}}`.

**Save** replaces the whole document with the text, in the order written. A field left out of the text is removed. A dotted name, or a name starting with `$` inside a subdocument, is stored as that exact name rather than read as a path. `_id` cannot change, and leaving it out keeps it.

If anyone changed or deleted the document after the sheet opened, nothing is saved and the sheet says so. Copy your text, close the sheet and open the document again.

## Writing queries

Queries run through JavaScriptCore, so a statement is JavaScript and the whole language is
available: object literals with unquoted keys, single-quoted strings, regex literals such as
`/abc/i`, `new Date()`, arithmetic, `//` and `/* */` comments.

`Date("2020-01-01")` without `new` gives a date rather than the string plain JavaScript would
return, so a filter written that way keeps matching. `new Date` and `instanceof Date` are the
native ones.

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

db.sales.aggregate([
  {$match: {date: {$gte: ISODate("2025-01-01")}}},
  {$group: {_id: "$product", totalSales: {$sum: "$amount"}}}
])
```

### Scripts

The shell is per connection, so a variable or function defined in one statement is there for the
next, in any tab on that connection, until you disconnect.

```javascript theme={null}
var stale = [];
db.orders.find({status: "pending"}).forEach(function (order) {
  if (order.updatedAt < ISODate("2025-01-01")) { stale.push(order._id); }
});
print("stale orders: " + stale.length);
```

`print` and `printjson` write to the result grid, one row per line, whenever the statement itself
returns no documents. A statement that returns documents shows those instead, with the printed
lines on the status line under the grid.

### Collection references

`db.users`, `db["users"]`, or `db.getCollection("users")`. Use `getCollection` for names with dots
or spaces, names starting with a digit, and names that collide with a database method: `db.stats`
and `db["stats"]` both reach the method, because the shell cannot tell which you meant.

### Cursors

`find()` and `aggregate()` return a cursor and touch nothing until something reads it. Chain
`sort`, `skip`, `limit`, `projection`, `hint`, `collation`, `maxTimeMS`, `batchSize` and
`allowDiskUse` onto it, then read it with `forEach`, `map`, `toArray`, `hasNext`/`next`, `itcount`,
`count` or `explain`. On an aggregation, `sort`, `skip` and `limit` become `$sort`, `$skip` and
`$limit` stages appended to the pipeline.

A modifier after the cursor has started throws, the same as mongosh. Split it into two statements,
or set the modifier before the first read.

### Write options

`updateOne`, `updateMany`, `replaceOne`, `findOneAndUpdate` and the delete calls take an options
document, and `upsert`, `arrayFilters`, `hint`, `collation` and `returnDocument` reach the server. A
write returns the object mongosh returns: `matchedCount`, `modifiedCount`, `upsertedCount` and
`upsertedId` for an update, `deletedCount` for a delete, `insertedId` for an insert.

```javascript theme={null}
db.users.updateOne({_id: 1}, {$set: {active: true}}, {upsert: true})
```

### Methods

Collection: `find`, `findOne`, `aggregate`, `countDocuments`/`count`, `estimatedDocumentCount`,
`distinct`, `insertOne`/`insertMany`/`insert`, `updateOne`/`updateMany`/`update`, `replaceOne`,
`save`, `deleteOne`/`deleteMany`/`remove`, `findOneAndUpdate`/`findOneAndReplace`/`findOneAndDelete`,
`bulkWrite`, `createIndex`/`createIndexes`, `dropIndex`/`dropIndexes`, `getIndexes`,
`hideIndex`/`unhideIndex`, `drop`, `renameCollection`, `stats`, `dataSize`, `storageSize`,
`totalIndexSize`, `totalSize`, `isCapped`, `validate`, `explain`.

Database: `getCollection`, `getSiblingDB`, `getCollectionNames`, `getCollectionInfos`,
`createCollection`, `dropDatabase`, `stats`, `version`, `serverStatus`, `hostInfo`, `currentOp`,
`killOp`, `runCommand`, `adminCommand`. `use <name>`, `show dbs` and `show collections` work as
typed. Anything with no method of its own goes through `db.runCommand({…})`.

`Cmd+Shift+F` reformats by nesting depth. Autocomplete offers collections, collection methods,
cursor methods after `find()`, nested field paths such as `address.city`, and the `$` operators
valid at the cursor; see [Autocomplete](/features/autocomplete#mongodb). For a query plan, chain
`.explain("executionStats")` onto the cursor.

## SSL/TLS

New connections default to **Disabled**, and the driver has no TLS fallback: **Preferred** behaves exactly as **Required**, which is what the SSL pane warns about. For an unencrypted local instance use **Disabled** or [SSH tunneling](/connections/ssh-tunneling). See [SSL/TLS](/connections/ssl).

## Limitations

* A row with no `_id` cannot be updated or deleted. The save is skipped rather than matched on the remaining fields. Keep `_id` in the projection so every row carries one.
* `_id` is read-only in the grid and in **Edit Document…**, and a row added with **Add Row** is inserted without one so the server generates it. To choose your own, use **Insert Document…**.
* **Edit Document…** opens a message instead of the text for a document it cannot write back exactly: a top-level field starting with `$`, a repeated field name, a subdocument shaped like `{"$numberInt": "5"}`, more than 28 levels of nesting, or a guarded save over 16 MB, which a document made mostly of numbers reaches at about 5 MB. Change such a document with `updateOne` in a query tab.
* The server replaces a top-level `Timestamp(0, 0)` with the current time whenever a whole document is written, so **Insert Document…** stores the time there and **Edit Document…** refuses a document holding one. `$set` in a query tab keeps it.
* **Edit Document…** also refuses a document holding a NaN, double or decimal, or JavaScript code with a scope. Change such a document with `updateOne` in a query tab.
* **Edit Document…** needs MongoDB 4.0 or later, and refuses a view and a time-series collection. Edit the collection a view reads, and change time-series documents with `updateMany` in a query tab.
* In a collection whose default collation is not simple, saving a document with a string `_id` reads the whole collection to find it. On a large collection, change the document with `updateOne` in a query tab instead.
* Transactions are not exposed. Statements always run standalone, on any topology.
* A collection takes one text index. A second **FULLTEXT** row fails after the collection and the indexes before it are created: list every text field in one index instead.
* **New Table…** writes the validator with the server's own level and action. To log bad documents instead of refusing them, run `db.runCommand({collMod: "articles", validationAction: "warn"})` after creating the collection.
* Nested paths filter but do not sort. Sorting works on the grid's own columns.
* **same element** covers a field one array deep. A path through an array inside another array needs nested `$elemMatch`, so those filter with dot notation only.
* GridFS buckets are not browsable, and change streams are unsupported.
* A script that loops without touching the database cannot be stopped: JavaScriptCore has no public way to interrupt one. `Cmd+.` stops anything that reads, writes or prints, which covers every query. A script silent for 120 seconds is abandoned and the shell restarts.
* Field names that look like integers (`"0"`, `"12"`) sort ahead of the rest in a document literal, which is what JavaScript does with them.

## Troubleshooting

**Connection refused**: check MongoDB is running (`brew services start mongodb-community`) and that the port and `bindIp` in `mongod.conf` match what you entered.

**Authentication fails on connect**: the error names the database that was authenticated against. If your user does not live there, set **Auth Database** in Advanced; otherwise check the username, password, and auth mechanism. The MQL editor does not parse `db.getUsers()` or `db.createUser()`; read users with `db.runCommand({"usersInfo": 1})`.

**Timeout**: for Atlas, add your IP to the cluster's access list first. Otherwise verify host and port and check the network and firewall.

**A collection is slow to open**: a sort or filter on an unindexed field makes MongoDB read every document, even for 20 rows. Check the Structure tab for an index on that field. `Cmd+.` stops the query on the server.

**The row total shows `~`**: that is the instant estimate from collection metadata. The automatic count is capped at 5 seconds and keeps the estimate if the server is slower; **Count Exactly** runs a real count against your query timeout. Views and time-series collections have no metadata count, so their estimate can be missing altogether.
