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

# MongoDB

> MongoDB 8.0 with transactions, change streams, a document browser, users, branches, sleep and backups, connected to your app through MONGODB_URI.

> [!TIP]
>
> **Live.** This area is documented as current, user-reliable behavior.

## Goal

Create a MongoDB database, connect your app with the official driver, then browse documents, manage users, branch, and move data in and out from the database page.

## Prerequisites

* A StackShift account
* A MongoDB driver or mongosh

## Workflow

**Step 1**

Open New, then Database, then MongoDB. You can start this from the databases page or from the project canvas add menu.

**Step 2**

Choose version 8.0, which is the only version offered, then pick a size. The smallest size has 1 GiB of memory.

**Step 3**

Choose where it runs: StackShift hosting or one of your own servers, then select Create.

**Step 4**

When the database is active, copy the connection string or the `mongosh` command from the database page.

**Step 5**

Link the database to your app so `MONGODB_URI` is set for you, then redeploy the app.

## Connection string

Linking a database to an app sets `MONGODB_URI`, with `MONGO_URL` and `MONGODB_URL` as aliases that hold the same value. `MONGODB_CA_CERT` holds the path to the CA file inside your app.

The string has this shape: `mongodb://<user>:<pass>@db-<id>.stackshift.internal:27017/<db>?tls=true&tlsCAFile=<path>&directConnection=true&authSource=<db>`.

`directConnection=true` keeps your app on one stable address for the database. Always keep it, and keep `tls=true` with the CA file.

## Connect from your code

```javascript Node.js theme={null}
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
const users = client.db().collection("users");
await users.insertOne({ name: "Ada" });
```

```python Python theme={null}
import os
import pymongo

client = pymongo.MongoClient(os.environ["MONGODB_URI"])
client.get_default_database()["users"].insert_one({"name": "Ada"})
```

```go Go theme={null}
import (
	"context"
	"os"

	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

client, err := mongo.Connect(options.Client().ApplyURI(os.Getenv("MONGODB_URI")))
if err != nil {
	panic(err)
}
defer client.Disconnect(context.Background())
```

## Transactions and change streams

Every MongoDB database on StackShift is set up for multi-document transactions, change streams and retryable writes. You do not turn anything on.

## Browse documents

* Open Data, then Documents. The list on the left shows each collection with its number of documents and its size.
* Type a filter as JSON, the same object you would pass to `find()`, for example `{ "status": "active" }`. Add a sort such as `{ "created_at": -1 }`, choose how many documents to show, then select Find.
* Select a document to open its full JSON. ObjectIds and dates show as `ObjectId('…')` and `ISODate('…')`.
* Insert adds a new document. Edit replaces a whole document and keeps its `_id`. Delete removes one document by its `_id`. Every change asks why you are making it and is recorded under your name. Changes that need an owner's approval wait for it.
* Indexes shows each index on the collection with its keys and whether it is unique, sparse or expires documents. Create or drop indexes from the shell or from your app.
* Views are listed with their collections and can be browsed, but not changed.

## Shell and query history

* The database page shows a ready `mongosh` command. Run it from a terminal that can reach the database.
* The Data tab has a shell for `mongosh` commands and keeps a history of your queries.
* The Metrics and Logs tabs show how the database is performing and what it has been doing. Metrics also counts slow operations.

## Users

* Add users in Settings, then Users and roles. Each user gets a role on the app database: Read only can find and read documents, Read and write can also add, change and delete documents and create collections and indexes, and Owner can do anything in the database, including dropping collections.
* Names are 3 to 32 characters: lowercase letters, numbers and `_`, starting with a letter. Names starting with `stackshift`, and `admin` and `root`, are kept for StackShift.
* StackShift makes the password. It is shown once when you add the user or reset its password. Copy it then.
* Deleting a user ends its open connections straight away.
* Users made in `mongosh` show as made in the shell. Change them with `mongosh` in Data, then Shell.

## Sleep

A MongoDB database can sleep when nothing is using it, like PostgreSQL and MySQL databases. The next connection wakes it. Your driver waits a second or two while it wakes, then carries on. Keep the driver's default `serverSelectionTimeoutMS` of 30 seconds.

Open connections that sit idle don't keep it awake, but running operations do, so an app that keeps reading a change stream never sleeps. A database with a standby doesn't sleep.

## Branches

* A branch is an instant copy of the database as it is now. It has its own address and password, and uses no extra space until you change data.
* Reset a branch to make it a fresh copy of its parent again. The branch page doesn't count documents written on MongoDB.
* To bring data from a branch into main, export it from the branch's Import and export tab and import it into main.

## Import and export

* Open Data, then Import and export. Export a copy writes a `mongodump` archive of the app database, compressed (`.archive.gz`) or plain (`.archive`).
* Import data loads an archive made with `mongodump --archive`, either uploaded or from an `https://` link. Choose a new database, or replace this one. Replacing loads into a spare copy first, checks it, and only switches when you select Use this data. You can undo for 24 hours.
* To copy from another MongoDB, such as Atlas, select Use a link or a MongoDB address and paste its `mongodb://` or `mongodb+srv://` address with a user and password. Add the database name to the end of the address when the user can see more than one database. MongoDB 4.2 to 8.x can be copied. The password is only used for the copy and isn't shown again.
* An archive from any single database lands in this database's app database. Users and the `admin`, `config` and `local` databases are left out.
* When the check passes, the transfer shows how many collections and documents were loaded.

## In a sandbox

Sandboxes can run MongoDB 8.0 as a temporary service. The sandbox gets `MONGODB_URI`, which points at the service on port 27017.

## Public access

The private address `db-<id>.stackshift.internal` is reachable only from your apps. To connect from your laptop, turn on public access in the database Settings, then use the connection string it shows.

## Backups

MongoDB databases are backed up automatically every day. On the Backups tab, pick a backup and restore it into this database or into another MongoDB database you own.

## Restore to any second

* On the Backups tab, turn on Keep history. StackShift then keeps every change from the oplog, so you can go back to the exact second before a mistake. It is included in paid plans. On the free plan the switch tells you to upgrade.
* The page shows the window you can restore to: from the latest full backup to the most recent second StackShift has saved, usually under a minute ago.
* Select Restore to a second, pick the time to the second in your own time zone, and choose another MongoDB database to restore into. Everything written during that second is included. The database you restore from keeps running unchanged.
* A time outside the window is refused with a message saying which times you can pick.

## Standby

* Turn on a standby in Settings. It is a second copy on another StackShift server that follows every change. If the main server is lost, the standby takes over and your app keeps the same address.
* It is billed at the same hourly price as the database and needs a paid plan and a backup that passed its restore check.
* Standbys run only on servers StackShift hosts for you. On your own servers, Settings says why it isn't available.

## Moving to another server

MongoDB databases move between servers like the other engines, for example when you change size or plan. The address and connection string stay the same.

## Limits

* Version 8.0 is the only version offered.
* The smallest size has 1 GiB of memory.

## Expected result

> [!TIP]
>
> Your app connects with its MongoDB driver, and `mongosh` opens a session on the database.

## Common failures

> [!WARNING]
>
> * Server selection timeout from outside StackShift: the private address only accepts connections from your apps. Turn on public access in Settings and use the public connection string.
> * TLS errors: keep `tls=true` and point `tlsCAFile` at the CA file from `MONGODB_CA_CERT`.
> * `not primary` or server discovery errors: keep `directConnection=true` in the connection string.

## Related guides

> [card] [Create a database](https://docs.stackshift.cloud/databases/create-a-database.md)
>
> Create a hosted or connected-node database with private, direct public, or StackShift tunnel access.

> [card] [Database connections and tunneling](https://docs.stackshift.cloud/databases/credentials-pooling-and-usage.md)
>
> Use private, direct public, or StackShift tunnel endpoints with TLS and explicit client IP policy.

> [card] [Back up and restore a database](https://docs.stackshift.cloud/databases/back-up-and-restore-a-database.md)
>
> Use durable recovery storage correctly and understand why backups are independent from portable SQL transfers.


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