Back up MongoDB
Create a consistent dump of a MongoDB database with mongodump, verify it, and prepare it for upload to Lighthouse.
Prerequisitesโ
- MongoDB Database Tools (
mongodump,mongorestore) โ these are a separate download from the server:- macOS:
brew install mongodb-database-tools - Debian/Ubuntu: install the MongoDB Database Tools package
- macOS:
- A connection string / URI with read access.
1. Sign in & create an API keyโ
You need a Lighthouse account, a workspace, and an API key before you can upload a backup.
-
Sign in to the portal and claim your free 5 GB workspace โ see Web Portal & Free Workspace.
-
Create an API key scoped
backup:write,backup:read,snapshots:readโ see API Keys. -
Export the credentials so the upload step can read them:
export LH_API_KEY="lh_xxxxxxxxxxxxxxxxxxxxxxxx"
export LH_WORKSPACE_ID="your-workspace-uuid"
Already have a key? Continue to the dump step below.
2. Create the dumpโ
Create the local dump directory once:
mkdir -p ./db-dumps
The cleanest output for backup is a single gzipped archive file (--archive + --gzip), which fits the "one stable file" pattern perfectly:
mongodump \
--uri="mongodb://user:pass@127.0.0.1:27017/app_db" \
--archive=./db-dumps/app.archive \
--gzip
| Flag | Why |
|---|---|
--uri | Full connection string (host, port, credentials, database). |
--archive=<file> | Write a single archive file instead of a directory tree โ ideal for upload. |
--gzip | Compress the archive. |
Dump the whole serverโ
Omit the database from the URI to dump every database:
mongodump --uri="mongodb://user:pass@127.0.0.1:27017" \
--archive=./db-dumps/all.archive --gzip
Directory output (alternative)โ
If you prefer the classic BSON directory layout:
mongodump --uri="mongodb://user:pass@127.0.0.1:27017/app_db" \
--out=./db-dumps/mongo --gzip
For replica sets, add --oplog to capture an oplog slice so the restore is consistent to a single point in time.
3. Verify the dumpโ
ls -lh ./db-dumps/app.archive
# Inspect archive contents without restoring:
mongorestore --archive=./db-dumps/app.archive --gzip --dryRun --verbose 2>&1 | head
4. Restore (recovery test)โ
Restore into a different database name to avoid touching the original:
mongorestore \
--uri="mongodb://user:pass@127.0.0.1:27017" \
--archive=./db-dumps/app.archive \
--gzip \
--nsFrom='app_db.*' --nsTo='app_db_restore.*'
5. Upload to Lighthouseโ
Your dump is now in ./db-dumps. After creating an authenticated SDK client with the API key from step 1, upload the directory as a snapshot:
snapshot, err := client.Backup([]string{"./db-dumps"}, &sdktypes.BackupOptions{})
if err != nil {
log.Fatal(err)
}
log.Printf("snapshotId=%s", snapshot.SnapshotID)
To run this on a schedule, use Automated backup with scheduling.
The dump command for this database, ready to drop into the scheduled job's make_dump():
mongodump --uri="$MONGO_URI" --archive=./db-dumps/app.archive --gzip