skip to content

Using mongorestore, how do you bring back one MongoDB collection from a nightly gzipped mongodump archive, and what happens to documents already there?

level: middleimportance: should knowfreq 42%

answer

  1. select by namespace, not by file
  2. two flags must match the dump
  3. inserts only, never updates
  4. what --drop does and doesn't remove
  5. read the summary line

basics

~10 s

Run mongorestore with --gzip, --archive and --nsInclude=db.collection. It only inserts, so a document whose _id already exists stays as it is and counts as a failure, unless --drop removes that collection first.

solid answer

~40 s

I run `mongorestore --gzip --archive=nightly.gz --nsInclude=sales.orders`, because `--gzip` and `--archive` have to match how the dump was made, and `--db` and `--collection` are deprecated for archive restores. `mongorestore` only inserts. A document whose `_id` already exists is left alone, the duplicate key error is logged, the tool carries on, and the summary line counts a failure, so the exit status can still be success. `--drop` drops the restored collection first and gives it a new UUID unless `--preserveUUID` is added. I usually restore beside the live data with `--nsFrom` and `--nsTo` and compare, since the collection holds a night's newer writes. Indexes are rebuilt from the dump's metadata after the documents load, so a big collection takes a while. `--oplogReplay` can't be combined with `--nsInclude`.

code

bash · 4 lines
bash
mongorestore --uri="mongodb://mongodb0.example.com:27017/?replicaSet=rs0" \
  --gzip --archive=/backups/nightly.archive.gz \
  --nsInclude="sales.orders" \
  --nsFrom="sales.orders" --nsTo="sales.orders_restored"

go deeper

for a junior

Recall the three flags for a compressed archive, and that a namespace is database plus collection. Remember that a restore inserts and never overwrites.

for a middle

Predict the result on a live collection: which documents return, which keep their newer values, what --drop changes, and why the summary line matters more than the exit status.

for a senior

Prefer a side restore under a new name when the collection is taking traffic, then merge deliberately. Know that --oplogReplay won't work with namespace filters, so the copy isn't rolled forward.

for a principal

Decide what a partial restore is for and rehearse it. An archive is convenient for transport and slow for one collection, so the dump format is a choice made for the restore you expect to run.

## The command `mongorestore` loads what `mongodump` wrote back into a running server. A **namespace** is a database and a collection joined by a dot, such as `sales.orders`. To restore one collection from a compressed archive, three flags do the work: - `--archive=<file>` reads the single-file format. Without a file name it reads standard input. - `--gzip` decompresses it. The docs say to pass both flags for a compressed archive. Leave `--gzip` off and the tool can't recognise the file as an archive. - `--nsInclude=<pattern>` selects by namespace, with `*` as a wildcard, and can be repeated. `--db` and `--collection` are deprecated when restoring from an archive, so `--nsInclude` is the form to learn. If you pass both `--nsInclude` and `--nsExclude`, the exclude wins. `--dryRun` with `--verbose` reports what would happen without importing anything, which is a cheap check before touching production. ## What happens to documents already there `mongorestore` is **insert only**. It can add to an existing database, but it doesn't update: - A document in the dump whose `_id` isn't in the collection is inserted. - A document whose `_id` already exists is **not overwritten**. The live version stays. - Documents that only exist in the live collection stay too. - By default the tool logs `continuing through error` for duplicate key and document validation errors and keeps going. `--stopOnError` makes it halt. So restoring over a live collection gives a mixture: old documents that were deleted come back, and documents changed since the dump keep their new values. That is sometimes what you want after a bad delete, and it's a surprise when you wanted the dump's version of everything. `--drop` changes the picture. It drops each collection being restored and then loads it fresh. It doesn't touch collections outside the restore, and a collection recreated this way gets a new UUID unless you add `--preserveUUID`. Everything written since the dump is gone from that collection. The safer habit when the collection is still taking traffic is a **side restore**: use `--nsFrom` and `--nsTo` to load `sales.orders` as `sales.orders_restored`, compare the two, and copy across only what you need. `--nsInclude` matches the name in the dump, before the rename. ## What the collection comes back with | Part | On restore | |---|---| | Documents | Inserted, in arbitrary order unless `--maintainInsertionOrder` is set | | Indexes | Rebuilt from metadata after the data, unless `--noIndexRestore` | | Collection options | Applied from metadata, unless `--noOptionsRestore` | | Write concern | `majority` by default, changed with `--writeConcern` | Throughput is set by `--numParallelCollections`, default 4, and `--numInsertionWorkersPerCollection`, default 1. For one big collection the second is the one to raise. ## Archive or directory An archive is a multiplexed stream. To pull out one namespace, `mongorestore` still reads through it and discards the data of every other collection, so time depends on the whole archive. A directory dump keeps one file per collection, and the tool skips what isn't included. If single-collection restores are common and the deployment is large, that favours a directory dump, or at least a test of how long one takes. ## Checking the result The exit status alone isn't proof. In Database Tools 100.20.1 duplicate key and validation failures don't change it, and a pattern that matches nothing restores no data and raises no error. 1. Read the summary line: documents restored and documents failed. 2. Compare the count with what you expected from the dump. 3. Confirm the indexes exist, since their build comes after the data. One limit is worth stating. `--oplogReplay` refuses `--nsInclude` and the other namespace filters, so a single collection from a nightly dump can't be rolled forward with the oplog file. Its documents are as `mongodump` read them, and if writes were running, those reads didn't all happen at one moment. ## If the restore goes wrong - **A crash.** If `mongorestore` crashes, only some of the data may be restored. The docs say to delete what was restored and start again from the beginning. - **A rollback on the target.** The same advice applies if the target cluster rolls back during the restore. - **Two at once.** MongoDB doesn't support several `mongorestore` programs running concurrently against one collection. - **The `-j` shortcut.** For a single collection, `-j` maps to `--numInsertionWorkersPerCollection` rather than `--numParallelCollections`.

  • What does mongorestore --drop do when the restore includes the admin database?
    It removes all user credentials and replaces them with the users in the dump. With `security.authorization` on, `mongorestore` must be able to authenticate both to an existing user and to a user defined in the dump. If it can't authenticate to the dump's user, the docs say the restore fails and leaves an empty database.
  • A one-collection restore from a 2 TB archive seems to take as long as the whole dump. Why?
    An archive interleaves every collection in one stream, and `mongorestore` has no way to jump to one namespace. It reads the stream through and discards data for namespaces outside `--nsInclude`. A directory dump has a file per collection, so the tool opens only the ones it needs.

  • mongorestore upserts, so restoring refreshes the documents that already exist.
  • --drop wipes the whole target database before the restore begins.
  • An exit status of zero means every document in the dump was inserted.
  • --nsInclude lets an archive restore jump straight to that collection's bytes.
  • mongorestore detects gzip by itself, so the --gzip flag can be left off.