# Protect MongoDB

> Backups, restore to any second, Proof, Rewind and Pulse for MongoDB 6.0, 7.0 and 8.0.

Source: https://rowsafe.sh/docs/guides/mongodb

Rowsafe protects MongoDB Community 6.0, 7.0 and 8.0 like PostgreSQL: encrypted backups in your bucket, restore to any second, a weekly Proof, Rewind and Pulse. Only connection pooling is left out: MongoDB's drivers pool on their own.

## Before you start

- MongoDB on Debian 12/13 or Ubuntu 22.04/24.04 (MongoDB's packages), or the official `mongo` Docker image.
- A **replica set** (one member is enough). Restoring to any second needs the oplog, which a standalone server doesn't keep. The installer can convert it for you.
- A bucket and an encryption passphrase. See [Adopt an existing database](https://rowsafe.sh/docs/guides/adopt).

## Turn on backups

Run this on the server, then approve the server in your browser when it prints the link:

```bash
curl -fsSL https://rowsafe.sh | sudo sh -s -- --account
```

The installer finds MongoDB and asks before changing anything.

**Tools.** If missing, it installs `mongodump` and `mongorestore` from MongoDB's apt repository (signing key fingerprint checked).

**Replica set.** If MongoDB is standalone, it asks *Turn on the replica set and restart MongoDB now?* (default no). Yes adds `replication.replSetName: rs0` (and a `keyFile` with access control) to the config, keeping a copy, and restarts once (a few seconds). If MongoDB doesn't start, the old config goes back. Apps connect as before.

**Rowsafe's MongoDB user.** It creates user `rowsafe` with a random password readable by the agent alone (`/var/lib/rowsafe/engines/mongodb/logins`). With access control on, an admin signs in once; that password is never saved. Its rights are [below](#what-rowsafe-may-do).

**What Rowsafe may do** on the server (restarts, updates, tuning, firewall), each only when someone clicks and confirms.

**The plan.** You review it and say yes. MongoDB's settings don't change. The agent starts copying the oplog, checks a fresh change arrives and opens with your key, then takes the first full backup.

On a server without PostgreSQL, the agent runs as its own system user, `rowsafe`.

Unattended: `--protect NAME` works too. It never restarts MongoDB unless you add `--mongodb-replica-set`, and reads an admin from `ROWSAFE_MONGODB_ADMIN_USER` and `ROWSAFE_MONGODB_ADMIN_PASSWORD` when needed (used once, never saved).

## What Rowsafe does

|                                                                      | How                                                                                                                                                                                                                                                                                                                                                                                    |
| -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Full backup                                                          | `mongodump --oplog --archive --gzip`, encrypted on your server. Daily at 01:00 UTC by default. No differential backups.                                                                                                                                                                                                                                                                |
| Every change                                                         | New oplog entries, uploaded as an encrypted chunk about once a minute.                                                                                                                                                                                                                                                                                                                 |
| Restore to any second                                                | The newest backup before that moment, then the oplog up to it (`mongorestore --oplogReplay`).                                                                                                                                                                                                                                                                                          |
| Marks                                                                | A note in the oplog (`appendOplogNote`), confirmed once its chunk is in your bucket. Exact.                                                                                                                                                                                                                                                                                            |
| Proof                                                                | Weekly: restore into a scratch `mongod` on a private Unix socket (no network), check databases, collections, indexes and counts, `validate` a few collections, then delete it.                                                                                                                                                                                                         |
| [Rewind](https://rowsafe.sh/docs/guides/restore)                                       | A copy at any second or Mark, kept up to 7 days on a private socket. Compare by `_id` and bring missing documents back (changed ones only if you ask). Dropped collections come back with their indexes.                                                                                                                                                                               |
| Rewind the whole database                                            | Puts every database (not `admin`, `config`, `local`) back in place. Restored privately while MongoDB runs, then each collection is swapped in by an instant rename. The old ones stay as `rowsafe_before_<tag>.<name>` for 7 days: **Undo rewind** or **Delete the old data now**. Views and users are untouched. Pause writing apps: a write during the swap may land on either side. |
| [Find the moment](https://rowsafe.sh/docs/guides/find-the-moment)                      | When documents were deleted or changed, or collections and databases dropped.                                                                                                                                                                                                                                                                                                          |
| Pulse                                                                | Connections, operations, queues, cache, write conflicts, oplog window, secondary lag, disk, operations over a minute. **Stop operation** (`killOp`, after checking it's the same one).                                                                                                                                                                                                 |
| Queries                                                              | Slow operations from the profiler, grouped by shape (values replaced by `?`). **Turn on query statistics** enables it for operations over 100 ms, no restart.                                                                                                                                                                                                                          |
| [Recommendations](https://rowsafe.sh/docs/guides/recommendations)                      | Wasteful operations (often a missing index), indexes unused for a week, and redundant indexes, with **Drop** (a Mark first).                                                                                                                                                                                                                                                           |
| Index suggestions                                                    | Collection scans become index ideas, tested on a restored copy with the recorded filter (values stay on your server). Suggested only if MongoDB uses it and reads at most half as many documents. **Create index** saves a Mark first.                                                                                                                                                 |
| [Logs](https://rowsafe.sh/docs/guides/logs)                                            | MongoDB's structured log, values removed on your server.                                                                                                                                                                                                                                                                                                                               |
| [Security](https://rowsafe.sh/docs/guides/security)                                    | Access control, exposure (also tested from the internet), TLS, old SCRAM-SHA-1 passwords, unsupported versions, the firewall. Access control and `bindIp` need a config change and restart, so they come with exact steps.                                                                                                                                                             |
| [Tuning](https://rowsafe.sh/docs/guides/tuning#mongodb-and-clickhouse)                 | Cache, connections, transaction length, slow threshold and profiler, explained, with **Tune for this server**. Written to the config file (a copy kept); some apply at once.                                                                                                                                                                                                           |
| Restart                                                              | **Restart** in the dashboard (or `rowsafe restart`), after you confirm. Rowsafe waits until MongoDB is primary again.                                                                                                                                                                                                                                                                  |
| [Updates](https://rowsafe.sh/docs/guides/updates#mysql-mariadb-mongodb-and-clickhouse) | New releases of your version (7.0.x) in one click; the next major (7.0 to 8.0, one at a time) rehearsed on a copy first, undo for 7 days.                                                                                                                                                                                                                                              |
| [Standby](https://rowsafe.sh/docs/guides/standby#mongodb)                              | A second server joins the replica set, never becomes primary by itself, and takes over when you promote it.                                                                                                                                                                                                                                                                            |
| [Fork](https://rowsafe.sh/docs/guides/fork#mongodb)                                    | A new database from any second or Mark, in an empty MongoDB on a server you pick.                                                                                                                                                                                                                                                                                                      |
| [Move in](https://rowsafe.sh/docs/guides/move-in#mongodb)                              | From MongoDB Atlas or any MongoDB, with live sync (change stream) and a switchover.                                                                                                                                                                                                                                                                                                    |
| [Databases & users](https://rowsafe.sh/docs/guides/databases-and-users)                | Databases and users with `read`, `readWrite` or `dbOwner` access, new passwords, removal (a Mark first). Passwords are made on your server and encrypted to your browser.                                                                                                                                                                                                              |
| Guard                                                                | [Preview a migration](https://rowsafe.sh/docs/guides/preview-migrations#other-engines) (mongosh calls) on a copy, and masked [safe copies](https://rowsafe.sh/docs/guides/safe-copies#other-engines).                                                                                                                                                                                                                      |
| [Files](https://rowsafe.sh/docs/guides/files)                                          | Your app's folders (uploads), restored to the same moment.                                                                                                                                                                                                                                                                                                                             |
| [Second copy](https://rowsafe.sh/docs/guides/second-copy)                              | Full backups and the oplog also go to a second bucket with its own passphrase; Proof alternates.                                                                                                                                                                                                                                                                                       |

Object names in your bucket only say *when*, never *what*.

## What Rowsafe may do

**Rowsafe's MongoDB user** (`rowsafe`, in `admin`) gets:

- `backup`, `clusterMonitor` and `readAnyDatabase`: backups, Proof, Pulse;
- `userAdminAnyDatabase` and `dbAdminAnyDatabase`: Databases & users;
- a role of its own, used only when someone asks: write a Mark, stop an operation, put documents back, turn the profiler on, create or drop an index, rename collections for a rewind, finish a major upgrade (`setFeatureCompatibilityVersion`), change settings (`setParameter`).

Two install options give more:

| Option                                                      | Gives                                                                                                                                                                    | For                                                                                                  |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- |
| `--mongodb-standby` (the installer asks on an empty server) | `clusterManager`; root's helper may hand out the replica set's key file and add `replSetName`, `keyFile` and an address to `mongod.conf` (a copy kept). Needs `restart`. | [Standby servers](https://rowsafe.sh/docs/guides/standby#mongodb), on both servers                                     |
| `--mongodb-clones` (the installer asks on an empty server)  | `restore` and `readWriteAnyDatabase`                                                                                                                                     | receiving a [fork](https://rowsafe.sh/docs/guides/fork#mongodb) or a database [moved in](https://rowsafe.sh/docs/guides/move-in#mongodb) |

**Root decides** what Rowsafe may do on the server itself ([permissions](https://rowsafe.sh/docs/guides/permissions), `sudo rowsafe-allow`):

| Permission                   | Lets Rowsafe                                                                                      |
| ---------------------------- | ------------------------------------------------------------------------------------------------- |
| `restart`                    | restart MongoDB (**Restart**)                                                                     |
| `updates`                    | install MongoDB's updates and major upgrades (needs `restart`)                                    |
| `security-updates`, `reboot` | install the server's security updates, and reboot it                                              |
| `tuning`                     | write the settings you change under Tuning into MongoDB's configuration file, only Rowsafe's keys |
| `firewall`                   | limit who can reach MongoDB's port                                                                |

Rewinding the whole database needs no root permission: it swaps collections inside MongoDB.

## Docker

Run the MongoDB agent image next to the official `mongo` image. It's built on that image, so the tools match your version:

```yaml
services:
  mongo:
    image: mongo:8.0
    hostname: mongo                 # the replica set records its member as mongo:27017
    command: ["--replSet", "rs0", "--bind_ip_all"]
    volumes:
      - mongodata:/data/db

  rowsafe-agent:
    image: ghcr.io/rowsafe/agent:<version>-mongo8
    hostname: db-1
    environment:
      ROWSAFE_MONGODB_HOST: mongo
    env_file: rowsafe-agent.env
    volumes:
      - rowsafe-state:/var/lib/rowsafe
```

Then, once:

```bash
docker compose exec rowsafe-agent rowsafe-agent mongodb initiate --port 27017
docker compose exec rowsafe-agent rowsafe-agent mongodb login --port 27017
rowsafe adopt shop --host db-1 --engine mongodb --port 27017
rowsafe apply shop
```

With `MONGO_INITDB_ROOT_USERNAME` set (access control on), add a `keyFile` for the replica set, and pass `--admin-user` to `mongodb login` (it asks for the password).

## Restore without Rowsafe

Decrypted, your backups are plain MongoDB formats. With the open-source agent and your passphrase:

```bash
export ROWSAFE_REPO_CIPHER_PASS='...'
rowsafe-agent unseal < archive.gz > dump.archive.gz
mongorestore --archive=dump.archive.gz --gzip --oplogReplay
```

Oplog chunks (`oplog/*.bson.gz`) decrypt the same way, for `mongorestore --oplogReplay --oplogFile`.

## Limits

- **No connection pooling**: MongoDB's drivers pool in every app.
- **Sharded clusters** (`mongos`) aren't supported. Replica sets (including a single server made into one) are.
- **Backups run on the primary**, where the agent runs. A secondary is skipped with a note.
- **Backups are logical** (`mongodump`), so large databases take longer to back up and restore than file copies. Proof shows how long a restore really takes.
- **Oplog gaps**: if the agent or bucket is down longer than the **oplog window** (Pulse shows it), that gap can't be restored. Rowsafe reports it and carries on; the next full backup starts a new chain. A bigger oplog (`replSetResizeOplog`) widens the window.
- **Bringing documents back** isn't one transaction. If it stops half-way, written documents stay; run it again to finish without duplicates.
- **Compare skips** views, time series collections, and collections over 10 million documents.
- **Rewinding the whole database** needs disk for a second copy, and the data goes through the oplog (give it room on big databases). Databases with time series collections can't be rewound in place.
- **Queries only see slow operations** (over 100 ms by default). Turned on from the dashboard, the profiler lasts until restart; [Tuning](https://rowsafe.sh/docs/guides/tuning#mongodb-and-clickhouse) or `operationProfiling.mode: slowOp` in `mongod.conf` keeps it on.
- **Index suggestions** need the profiler, and only come from plain filters (no `$or`, `$expr` or text search).
- **Find the moment** groups non-transaction deletes and updates by collection and second. "Just before" restores to the second before.
- **In Docker**, restart the container yourself (Rowsafe notices). Tuning and standbys need the agent on the server. Update by pulling the newest image of the same version.
- **Settings MongoDB reads only at start** wait for the next restart.
- **Forks hold the real data.** Use a [safe copy](https://rowsafe.sh/docs/guides/safe-copies) for masked data.
- **Older installs**: a user created before Databases & users, index suggestions or rewind in place can list but not change. Run the install command again once (the dashboard shows it).
