mongorestore
macOS Sierra and Go 1.6 Incompatibility
Users running on macOS Sierra require the 3.2.10 or newer versionof mongorestore.
Synopsis
The mongorestore
program loads data from either a binarydatabase dump created by mongodump
or the standard input(starting in version 3.0.0) into a mongod
ormongos
instance.
Availability
The mongorestore
tool is part of the MongoDB tools package. Consult theinstallation guide for your platform forinstructions on how to install the tools package as part of yourMongoDB installation.
The tools package is also available from theMongoDB Download Center,either as a separate tools
download, or contained within theTGZ
or ZIP
downloads, depending on platform. On Windows, the MSI
installer includes all tools as part of the default installation.
Tip
If downloading the TGZ
or ZIP
files from the DownloadCenter, you may want to update your PATH
environmentvariable to include the directory where you installed these tools.See the installation guidefor your platform for more information.
Usage in Backup Strategy
Standalones/Replica Sets
For an overview of mongorestore
usage as part of abackup and recovery strategy, seeBack Up and Restore with MongoDB Tools.
Sharded Clusters
mongodump
and mongorestore
cannot be part of a backup strategy for 4.2+ sharded clustersthat have sharded transactions in progress as these tools cannotguarantee a atomicity guarantees of data across the shards.
For 4.2+ sharded clusters with in-progress sharded transactions, forcoordinated backup and restore processes that maintain the atomicityguarantees of transactions across shards, see:
Syntax
Run mongorestore
from the system command line, not the mongo
shell.
- mongorestore [options] [<directory>/<BSON file>]
For example, to restore from a dump
directory to a localmongod
instance running on port 27017
:
- mongorestore dump/
As mongorestore
restores from the dump/
directory,it creates the database and collections as needed and logs its progress:
- 2019-07-08T14:37:38.942-0400 preparing collections to restore from
- 2019-07-08T14:37:38.944-0400 reading metadata for test.bakesales from dump/test/bakesales.metadata.json
- 2019-07-08T14:37:38.944-0400 reading metadata for test.salaries from dump/test/salaries.metadata.json
- 2019-07-08T14:37:38.976-0400 restoring test.salaries from dump/test/salaries.bson
- 2019-07-08T14:37:38.985-0400 no indexes to restore
- 2019-07-08T14:37:38.985-0400 finished restoring test.salaries (10 documents, 0 failures)
- 2019-07-08T14:37:39.009-0400 restoring test.bakesales from dump/test/bakesales.bson
- 2019-07-08T14:37:39.011-0400 restoring indexes for collection test.bakesales from metadata
- 2019-07-08T14:37:39.118-0400 finished restoring test.bakesales (21 documents, 0 failures)
- 2019-07-08T14:37:39.118-0400 restoring users from dump/admin/system.users.bson
- 2019-07-08T14:37:39.163-0400 restoring roles from dump/admin/system.roles.bson
- 2019-07-08T14:37:39.249-0400 31 document(s) restored successfully. 0 document(s) failed to restore.
You can also restore a specific collection or collections from thedump/
directory. For example, the following operation restores asingle collection from corresponding data files in the dump/
directory:
- mongorestore --nsInclude=test.purchaseorders dump/
If the dump/
directory does not contain the corresponding data filefor the specified namespace, no data will be restored. For example, thefollowing specifies a collection namespace that does not have acorresponding data in the dump/
directory:
- mongorestore --nsInclude=foo.bar dump/
The mongorestore
outputs the following messages:
- 2019-07-08T14:38:15.142-0400 preparing collections to restore from
- 2019-07-08T14:38:15.142-0400 0 document(s) restored successfully. 0 document(s) failed to restore.
For more examples, see Examples.
For more information on the options and arguments, seeOptions.
Behavior
Insert Only
mongorestore
can create a new database or add data to anexisting database. However, mongorestore
performs insertsonly and does not perform updates. That is, if restoring documents toan existing database and collection and existing documents have thesame value id
field as the to-be-restored documents,mongorestore
will _not overwrite those documents.
Rebuild Indexes
mongorestore
recreates indexes recorded bymongodump
.
Note
For MongoDB 2.6 through MongoDB versions withfeatureCompatibilityVersion
(fCV) set to "4.0"
or earlier,creating indexes will error if anindex key in an existing document exceeds the limit
.
To avoid this issue, consider using hashed indexes or indexing acomputed value instead. If you want to resolve the index issue afterrestoring the data, you can disable the default index key lengthvalidation on the target database by setting the mongodinstance’s failIndexKeyTooLong
parameter to false.
Version Compatibility
The data format used by mongodump
from version 2.2 orlater is incompatible with earlier versions of mongod
.Do not use recent versions of mongodump
to back up olderdata stores.
Exclude system.profile Collection
mongorestore
does not restore the system.profile
collection data.
FIPS
Starting in version 4.2, MongoDB removes the —sslFIPSMode
option for mongorestore. mongorestorewill use FIPS compliant connections tomongod
/mongos
if themongod
/mongos
instances areconfigured to use FIPS mode.
Write Concern
Starting in version 4.2, if you specify write concern in both the—writeConcern
option and the—uri
connection string option, the—writeConcern
value overridesthe write concern specified in the URI string.
In earlier versions, the two options are incompatible.
Required Access
To restore data to a MongoDB deployment that has access control enabled, the restore
role providesthe necessary privileges to restore data from backups if the data doesnot include system.profile
collection data and you run mongorestore
without the—oplogReplay
option.
If the backup data includes system.profile
collection data or you run with—oplogReplay
, you needadditional privileges:
system.profile | If the backup data includes system.profile collection data and the target databasedoes not contain the system.profile collection, mongorestore attempts to create the collectioneven though the program does not actually restore system.profile documents. As such, the user requires additional privileges to performcreateCollection and convertToCapped actions on the system.profile collection for a database.Both the built-in roles dbAdmin anddbAdminAnyDatabase provide the additional privileges. |
—oplogReplay | To run with —oplogReplay , create a user-defined role that has anyAction onanyResource.Grant only to users who must run mongorestore with —oplogReplay . |
Options
Changed in version 3.0.0: mongorestore
removed the —filter
, —dbpath
, and the—noobjcheck
options.
—verbose
,
-v
- Increases the amount of internal reporting returned on standard outputor in log files. Increase the verbosity with the
-v
form byincluding the option multiple times, (e.g.-vvvvv
.)
This option suppresses:
- output from database commands
- replication activity
- connection accepted events
- connection closed events
New in version 3.4.6.
Specify a resolvable URIconnection string (enclose in quotes) to connect to the MongoDB deployment.
- --uri="mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]"
For information on the components of the connection string, seethe Connection String URI Format documentation.
Note
For TLS/SSL options, use the command-line options instead of theURI options for TLS/SSL (Available starting in4.2).
Important
The following command-line options cannot be used in conjunctionwith —uri
option:
—host
—port
—db
—username
—password
(if theURI connection string also includes the password)—authenticationDatabase
—authenticationMechanism
Instead, specify these options as part of your—uri
connection string.
Specifies a resolvable hostname for the mongod
to which toconnect. By default, the mongorestore attempts to connect to a MongoDBinstance running on the localhost on port number 27017
.
To connect to a replica set, specify thereplSetName
and a seed list of set members, as inthe following:
- --host=<replSetName>/<hostname1><:port>,<hostname2><:port>,<...>
When specifying the replica set list format, mongorestore always connects tothe primary.
You can also connect to any single member of the replica set by specifyingthe host and port of only that member:
- --host=<hostname1><:port>
Changed in version 3.0.0: If you use IPv6 and use the <address>:<port>
format, you mustenclose the portion of an address and port combination inbrackets (e.g. [<address>]
).
Note
You cannot specify both —host
and —uri
.
Specifies the TCP port on which the MongoDB instance listens forclient connections.
Note
You cannot specify both —port
and —uri
.
New in version 2.6.
Enables connection to a mongod
or mongos
that hasTLS/SSL support enabled.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 2.6.
Specifies the .pem
file that contains the root certificate chainfrom the Certificate Authority. Specify the file name of the.pem
file using relative or absolute paths.
Starting in version 3.4, if —tlsCAFile
/net.tls.CAFile
(ortheir aliases —sslCAFile
/net.ssl.CAFile
) is not specifiedand you are not using x.509 authentication, the system-wide CAcertificate store will be used when connecting to an TLS/SSL-enabledserver.
To use x.509 authentication, —tlsCAFile
or net.tls.CAFile
must be specified unless using —tlsCertificateSelector
or—net.tls.certificateSelector
. Or if using the ssl
aliases,—sslCAFile
or net.ssl.CAFile
must be specified unless using—sslCertificateSelector
or net.ssl.certificateSelector
.
Warning
Version 3.2 and earlier: For TLS/SSL connections (—ssl
) tomongod
and mongos
, if the mongorestore runs without the—sslCAFile
, mongorestore will not attemptto validate the server certificates. This creates a vulnerabilityto expired mongod
and mongos
certificates aswell as to foreign processes posing as valid mongod
ormongos
instances. Ensure that you always specify theCA file to validate the server certificates in cases whereintrusion is a possibility.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 2.6.
Specifies the .pem
file that contains both the TLS/SSL certificateand key. Specify the file name of the .pem
file using relativeor absolute paths.
This option is required when using the —ssl
option to connectto a mongod
or mongos
that hasCAFile
enabled withoutallowConnectionsWithoutCertificates
.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 2.6.
Specifies the password to de-crypt the certificate-key file (i.e.—sslPEMKeyFile
). Use the —sslPEMKeyPassword
option only if thecertificate-key file is encrypted. In all cases, the mongorestore willredact the password from all logging and reporting output.
If the private key in the PEM file is encrypted and you do not specifythe —sslPEMKeyPassword
option, the mongorestore will prompt for a passphrase. SeeTLS/SSL Certificate Passphrase.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 2.6.
Specifies the .pem
file that contains the Certificate RevocationList. Specify the file name of the .pem
file using relative orabsolute paths.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 2.6.
Bypasses the validation checks for server certificates and allowsthe use of invalid certificates. When using theallowInvalidCertificates
setting, MongoDB logs as awarning the use of the invalid certificate.
Starting in MongoDB 4.0, if you specify—sslAllowInvalidCertificates
ornet.ssl.allowInvalidCertificates: true
(or in MongoDB 4.2, thealias —tlsAllowInvalidateCertificates
ornet.tls.allowInvalidCertificates: true
) when using x.509authentication, an invalid certificate is only sufficient toestablish a TLS/SSL connection but is insufficient forauthentication.
Warning
Although available, avoid using the—sslAllowInvalidCertificates
option if possible. If the use of—sslAllowInvalidCertificates
is necessary, only use the optionon systems where intrusion is not possible.
If the mongo
shell (and otherMongoDB Tools) runs with the—sslAllowInvalidCertificates
option, themongo
shell (and otherMongoDB Tools) will not attempt to validatethe server certificates. This creates a vulnerability to expiredmongod
and mongos
certificates aswell as to foreign processes posing as validmongod
or mongos
instances. If youonly need to disable the validation of the hostname in theTLS/SSL certificates, see —sslAllowInvalidHostnames
.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 3.0.
Disables the validation of the hostnames in TLS/SSL certificates. Allowsmongorestore to connect to MongoDB instances even if the hostname in theircertificates do not match the specified hostname.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
—username
=<username>
,
-u
=<username>
- Specifies a username with which to authenticate to a MongoDB databasethat uses authentication. Use in conjunction with the
—password
and—authenticationDatabase
options.
Note
You cannot specify both —username
and —uri
.
—password
=<password>
,
-p
=<password>
- Specifies a password with which to authenticate to a MongoDB databasethat uses authentication. Use in conjunction with the
—username
and—authenticationDatabase
options.
Changed in version 3.0.2: To prompt the userfor the password, pass the —username
option without—password
or specify an empty string as the —password
value,as in —password=""
.
Note
You cannot specify both —password
and —uri
.
—authenticationDatabase
=<dbname>
- Specifies the authentication database where the specified
—username
has been created.See Authentication Database.
Note
You cannot specify both —authenticationDatabase
and —uri
.
Specifies the authentication mechanism the mongorestore instance uses toauthenticate to the mongod
or mongos
.
Changed in version 4.0: MongoDB removes support for the deprecated MongoDBChallenge-Response (MONGODB-CR
) authentication mechanism.
MongoDB adds support for SCRAM mechanism using the SHA-256 hashfunction (SCRAM-SHA-256
).
ValueDescriptionSCRAM-SHA-1RFC 5802 standardSalted Challenge Response Authentication Mechanism using the SHA-1hash function.SCRAM-SHA-256RFC 7677 standardSalted Challenge Response Authentication Mechanism using the SHA-256hash function.
Requires featureCompatibilityVersion set to 4.0
.
New in version 4.0.
MONGODB-X509MongoDB TLS/SSL certificate authentication.GSSAPI (Kerberos)External authentication using Kerberos. This mechanism isavailable only in MongoDB Enterprise.PLAIN (LDAP SASL)External authentication using LDAP. You can also use PLAIN
for authenticating in-database users. PLAIN
transmitspasswords in plain text. This mechanism is available only inMongoDB Enterprise.
Note
You cannot specify both —authenticationMechanism
and —uri
.
New in version 2.6.
Specify the name of the service using GSSAPI/Kerberos. Only required if the service does not use thedefault name of mongodb
.
This option is available only in MongoDB Enterprise.
New in version 2.6.
Specify the hostname of a service using GSSAPI/Kerberos. Only required if the hostname of a machine doesnot match the hostname resolved by DNS.
This option is available only in MongoDB Enterprise.
—db
=<database>
,
-d
=<database>
- Specifies the destination database for mongorestore to restore datainto when restoring from a BSON file. If the database does notexist, mongorestore creates the database. For example, the followingrestores the
salaries
collection into thereporting
database.
- mongorestore --db=reporting dump/test/salaries.bson
If you do not specify —db
, mongorestore takes the database namefrom the data files.
The use of —db
and —collection
options aredeprecated when restoring from a directory or an archive file.Instead, to restore from an archive or a directory, see—nsInclude
instead.
Note
You cannot specify both —db
and —uri
.
—collection
=<collection>
,
-c
=<collection>
- Specifies the name of the destination collection for mongorestore torestore data into when restoring from a BSON file. Ifyou do not specify
—collection
, mongorestore takesthe collection name from the input filename. If the input file has anextension, MongoDB omits the extension of the file from the collectionname.
- mongorestore --db=reporting --collection=employeesalaries dump/test/salaries.bson
The use of —db
and —collection
options aredeprecated when restoring from a directory or an archive file.Instead, to restore from an archive or a directory, see—nsInclude
instead.
New in version 3.4.
Specifies a namespace pattern (e.g. "test.myCollection"
,"reporting."
, "dept
.bar"
) to exclude the matchingnamespaces from the restore. In the pattern, you can use asterisks*
as wild cards. For an example of the wildcard pattern, seeRestore Collections Using Wild Cards.
You can specify —nsExclude
multiple times to exclude multiple namespacepatterns.
New in version 3.4.
Specifies a namespace pattern (e.g. "test.myCollection"
,"reporting."
, "dept
.bar"
) to restore only the namespacesthat match the pattern. In the pattern, you can use asterisks *
as wild cards. For an example of the wildcard pattern, seeRestore Collections Using Wild Cards.
You can specify —nsInclude
multiple times to include multiple namespacepatterns.
If source directory or file (i.e. the directory/file from which youare restoring the data) does not contain data files that match thenamespace pattern, no data will be restored.
For collection names that contain non-ascii characters,mongodump
outputs the corresponding filenames withpercent-encoded names. However, to restore these collections, do notuse the encoded names. Instead, use the namespace with the non-asciicharacters.
For example, if the dump directory containsdump/test/caf%C3%A9s.bson
, specify —nsInclude "test.cafés"
.
New in version 3.4.
Use with —nsTo
to rename a namespace during therestore operation. —nsFrom
specifies the collection in thedump file, while —nsTo
specifies the name that should beused in the restored database.
—nsFrom
accepts a namespace pattern as its argument. The namespacepattern permits —nsFrom
to refer to any namespace that matches thespecified pattern. mongorestore
matches the smallest valid occurenceof the namespace pattern.
For simple replacements, use asterisks (*
) as wild cards.Escape all literal asterisks and backslashes with a backslash.Replacements correspond linearly to matches: each asterisk in—nsFrom
must correspond to an asterisk in —nsTo
, and thefirst asterisk in —nsFrom
matches the first asterisk in nsTo
.
For more complex replacements, use dollar signs to delimit a “wildcard” variable to use in the replacement.Change Collections’ Namespaces during Restore provides an example of complexreplacements with dollar sign-delimited wild cards.
Unlike replacements with asterisks, replacements with dollarsign-delimited wild cards do not need to be linear.
New in version 3.4.
Use with —nsFrom
to rename a namespace during therestore operation. —nsTo
specifies the new collectionname to use in the restored database, while—nsFrom
specifies the name in the dump file.
—nsTo
accepts a namespace pattern as its argument. The namespacepattern permits —nsTo
to refer to any namespace that matches thespecified pattern. mongorestore
matches the smallest valid occurenceof the namespace pattern.
For simple replacements, use asterisks (*
) as wild cards.Escape all literal asterisks and backslashes with a backslash.Replacements correspond linearly to matches: each asterisk in—nsFrom
must correspond to an asterisk in —nsTo
, and thefirst asterisk in —nsFrom
matches the first asterisk in nsTo
.
For more complex replacements, use dollar signs to delimit a “wildcard” variable to use in the replacement.Change Collections’ Namespaces during Restore provides an example of complexreplacements with dollar sign-delimited wild cards.
Unlike replacements with asterisks, replacements with dollarsign-delimited wild cards do not need to be linear.
—objcheck
- Forces mongorestore to validate all requests from clientsupon receipt to ensure that clients never insert invalid documents intothe database. For objects with a high degree of sub-document nesting,
—objcheck
can have a small impact on performance.
—drop
- Before restoring the collections from the dumped backup, drops thecollections from the target database.
—drop
does not dropcollections that are not in the backup.
When the restore includes the admin
database, mongorestore with—drop
removes all user credentials and replaces them with theusers defined in the dump file. Therefore, in systems withauthorization
enabled, mongorestore must be ableto authenticate to an existing user and to a user defined in thedump file. If mongorestore can’t authenticate to a user defined in thedump file, the restoration process will fail, leaving an emptydatabase.
New in version 3.4.
Runs mongorestore without actually importing any data, returning themongorestore summary information. Use with —verbose
to producemore detailed summary information.
—oplogReplay
- After restoring the database dump, replays the oplog entriesfrom a bson file.When used in conjunction with
mongodump —oplog
,mongorestore —oplogReplay
restores the database to the point-in-time backup captured with themongodump —oplog
command.
mongorestore searches for any valid source for the bson filein the following locations:
- The top level of the dump directory, as in the case of a dump createdwith
mongodump —oplog
. - The path specified by
—oplogFile
. <dump-directory>/local/oplog.rs.bson
, as in the case of a dumpof theoplog.rs
collection in thelocal
databaseon amongod
that is a member of a replica set.If there is anoplog.bson
file at the top level of the dumpdirectory and a path specified by—oplogFile
,mongorestore returns an error.
If there is an oplog.bson
file at the top level of the dump directory,mongorestore restores that file as the oplog. If there are also bsonfiles in the dump/local
directory, mongorestore restores them likenormal collections.
If you specify an oplog file using —oplogFile
,mongorestore restores that file as the oplog. If there are also bsonfiles in the dump/local
directory, mongorestore restores them likenormal collections.
For an example of —oplogReplay
, see Restore Point in Time Oplog Backup.
Note
When using mongorestore
with —oplogReplay
to restorea replica set, you mustrestore a full dump of a replica set member createdusing ~bin.mongodump —oplog
.mongorestore
with —oplogReplay
fails if you use any ofthe following options to limit the data be restored:
See also
See also
—oplogLimit
=<timestamp>
- Prevents mongorestore from applying oplog entrieswith timestamp newer than or equal to
<timestamp>
. Specify<timestamp>
values in the form of<time_t>:<ordinal>
, where<time_t>
is the seconds since the UNIX epoch, and<ordinal>
represents a counter of operations in the oplog that occurred in thespecified second.
You must use —oplogLimit
in conjunction with the—oplogReplay
option.
New in version 3.4.
Specifies the path to the oplog file containing oplog data for therestore. Use with —oplogReplay
.
If you specify —oplogFile
and there is an oplog.bson
file at the top level of the dump directory, mongorestore returns anerror.
—keepIndexVersion
- Prevents mongorestore from upgrading the index to the latestversion during the restoration process.
—noIndexRestore
- Prevents mongorestore from restoring and building indexes asspecified in the corresponding
mongodump
output.
—noOptionsRestore
- Prevents mongorestore from setting the collection options,such as those specified by the
collMod
databasecommand, on restored collections.
—restoreDbUsersAndRoles
- Restore user and role definitions for the given database. Seesystem.roles Collection andsystem.users Collection for more information.
Specifies the write concern for each write operation that mongorestoreperforms.
Specify the write concern as a document with w options:
- --writeConcern="{w:'majority'}"
If the write concern is also included in the —uriconnection string
, the command-line—writeConcern
overrides the write concern specified inthe URI string.
If specified,
- Starting in version 4.2, mongorestore inserts the documents in theorder of their appearance in the input source. That is, both thebulk write batch order and document order within the batches aremaintained.
- In earlier versions, only the batch order is maintained; documentorder within batches are not maintained.Starting in MongoDB 4.2,specifying
—maintainInsertionOrder
also enables—stopOnError
and setsnumInsertionWorkersPerCollection
to 1.
If unspecified, mongorestore may perform the insertions in anarbitrary order.
Number of collections mongorestore should restorein parallel.
If you specify -j
when restoring a single collection, -j
maps to the —numInsertionWorkersPerCollection
option rather than—numParallelCollections
.
New in version 3.0.0.
Specifies the number of insertion workers to run concurrently per collection.
For large imports, increasing the number of insertion workersmay increase the speed of the import.
New in version 3.0.
Forces mongorestore to halt the restore when it encounters anerror.
Starting in version 4.2, mongorestore
, by default,continues when it encounters duplicate key and documentvalidation errors. To ensure that the program stops on these errors, specify —stopOnError
.
—bypassDocumentValidation
- Enables mongorestore to bypass document validationduring the operation. This lets you insert documents that do notmeet the validation requirements.
New in version 3.2.1.
New in version 3.2.
Restores from compressed files or data stream created by~bin.mongodump —gzip
To restore from a dump directory that contains compressed files, runmongorestore
with the —gzip
option.
To restore from a compressed archive file, run mongorestore
withboth the —gzip
and the –archive options.
New in version 3.2.
Restores from the specified archive file or, if the file isunspecified, from the standard input (stdin
):
- To restore from an archive file, run mongorestore withthe
—archive
option and the archive filename - To restore from the standard input, run mongorestorewith the
—archive
option but omit the filename.
Note
- mongorestore still supports the positional
-
parameter torestore a single collection from the standard input.
You cannot specify both the <path>
argument and the —dir
option, which also specifies the dump directory, to mongorestore.
—dir
=string
Specifies the dump directory.
- You cannot specify both the
—dir
option and the<path>
argument, which also specifies the dump directory, to mongorestore. - You cannot use the
—archive
option with the—dir
option.
- You cannot specify both the
Examples
Restore with Access Control
In the following example, mongorestore
restores from/opt/backup/mongodump-2011-10-24
to a mongod
instance running on port 27017
on the hostmongodb1.example.net
. The —uri
string omits the user’s password to have mongorestore
prompt for the password.
- mongorestore --uri="mongodb://user@mongodb1.example.net:27017/?authSource=admin" /opt/backup/mongodump-2011-10-24
Alternatively, you can specify the host, port, username, andauthentication database using —host
,—port
, —username
, and —authenticationDatabase
. Omit —password
to have mongorestore
prompt for the password:
- mongorestore --host=mongodb1.example.net --port=27017 --username=user --authenticationDatabase=admin /opt/backup/mongodump-2011-10-24
Restore a Collection
New in version 3.4.
To restore a specific collection, use —nsInclude
, passing in the full namespace(<database>.<collection>
) of the collection.
For example, the following restores the collection namedpurchaseorders
in the database test
from the correspondingfiles located in the dump/
directory.
- mongorestore --nsInclude=test.purchaseorders dump/
The mongorestore
outputs the results, including thenumber of documents restored:
- 2019-06-28T19:23:42.858-0400 preparing collections to restore from
- 2019-06-28T19:23:42.858-0400 reading metadata for test.purchaseorders from dump/test/purchaseorders.metadata.json
- 2019-06-28T19:23:42.893-0400 restoring test.purchaseorders from dump/test/purchaseorders.bson
- 2019-06-28T19:23:42.896-0400 restoring indexes for collection test.purchaseorders from metadata
- 2019-06-28T19:23:42.991-0400 finished restoring test.purchaseorders (6 documents, 0 failures)
- 2019-06-28T19:23:42.991-0400 6 document(s) restored successfully. 0 document(s) failed to restore.
If the dump/
directory does not contain the corresponding datafiles for the specified namespace, no data will be restored:
- 2019-07-08T14:39:57.121-0400. preparing collections to restore from
- 2019-07-08T14:39:57.121-0400 0 document(s) restored successfully. 0 document(s) failed to restore.
Alternatively, you can restore a specific collection using the—db
, —collection
, and a .bson
file:
- mongorestore --db=test --collection=purchaseorders dump/test/purchaseorders.bson
- 2019-06-30T12:21:44.777-0400 checking for collection data in dump/test/purchaseorders.bson
- 2019-06-30T12:21:44.779-0400 reading metadata for test.purchaseorders from dump/test/purchaseorders.metadata.json
- 2019-06-30T12:21:44.813-0400 restoring test.purchaseorders from dump/test/purchaseorders.bson
- 2019-06-30T12:21:44.881-0400 restoring indexes for collection test.purchaseorders from metadata
- 2019-06-30T12:21:44.987-0400 finished restoring test.purchaseorders (6 documents, 0 failures)
- 2019-06-30T12:21:44.987-0400 6 document(s) restored successfully. 0 document(s) failed to restore.
Restore Collections Using Wild Cards
New in version 3.4.
—nsInclude
and—nsExclude
support specifying thenamespaces you wish to include or exclude from arestore operation using asterisks as wild cards.
The following example restores the documents in the dump/
sub-directory of the current directory that match the specifiednamespace pattern. The —nsInclude
statement specifies to only restore documents in the transactions
database while —nsExclude
instructs mongorestore
to exclude collections whosenames end with _dev
. mongorestore
restores data tothe mongod
instance running on the localhost interfaceon port 27017
.
- mongorestore --nsInclude='transactions.*' --nsExclude='transactions.*_dev' dump/
Change Collections’ Namespaces during Restore
New in version 3.4.
MongoDB 3.4 added the —nsFrom
and—nsTo
options, which enable you tochange the namespace of a collection that you are restoring.—nsFrom
and —nsTo
support using asterisks as wild cards _and_support using dollar signs to delimit “wild card” variables to use inthe replacement.
Consider a database data
that you have exported to a dump/
directory using mongodump
. The data
databasecontains the following collections:
sales_customer1
sales_customer2
sales_customer3
users_customer1
users_customer2
users_customer3
Using —nsFrom
and —nsTo
, you can restore the data into differentnamespaces. The following operation
- restores the
sales_<customerName>
collections in thedata
database tosales
collections in the<customerName>
database,and - restores the
users_<customerName>
collections tousers
collections in the<customerName>
database.
- mongorestore --nsInclude='data.*' --nsFrom='data.$prefix$_$customer$' --nsTo='$customer$.$prefix$'
Copy/Clone a Database
Starting in version 4.2, MongoDB removes the deprecated copydb
command and clone
command.
As an alternative, users can use mongodump
andmongorestore
(with the mongorestore
options—nsFrom
and —nsTo
).
For example, to copy the test
database from a local instancerunning on the default port 27017 to the examples
database on thesame instance, you can:
- Use
mongodump
to dump thetest
database toan archivemongodump-test-db
:
- mongodump --archive="mongodump-test-db" --db=test
- Use
mongorestore
with—nsFrom
and—nsTo
to restore (with database name change) from thearchive:
- mongorestore --archive="mongodump-test-db" --nsFrom='test.*' --nsTo='examples.*'
Tip
Include additional options as necessary, such as to specifythe uri or host, username, password and authenticationdatabase.
Alternatively, instead of using an archive file, you canmongodump
the test
database to the standardoutput stream and pipe into mongorestore
:
- mongodump --archive --db=test | mongorestore --archive --nsFrom='test.*' --nsTo='examples.*'
Restore from an Archive File
To restore from an archive file, run restore
with the new—archive
option and the archive filename.
- mongorestore --archive=test.20150715.archive
Restore a Database from an Archive File
New in version 3.2.
To restore from an archive file, run restore
with the new—archive
option and the archive filename. For example, thefollowing operation restores the test
database from the filetest.20150715.archive
.
- mongorestore --archive=test.20150715.archive --nsInclude="test.*"
Restore from Compressed Data
New in version 3.2: With the —gzip
option, mongorestore
can restore fromcompressed files or data stream created by mongodump
.
To restore from a dump directory that contains compressed files, runmongorestore
with the —gzip
. For example, the following operation restores the test
database from the compressed files located in the default dump
directory:
- mongorestore --gzip --nsInclude="test.*" dump/
To restore from a compressed archive file, runmongorestore
with the —gzip
option and the —archive
option. For example, the following operation restores the test
database from the archive file test.20150715.gz
.
- mongorestore --gzip --archive=test.20150715.gz --nsInclude="test.*"
Restore a Database from Standard Input
New in version 3.2.
To restore from the standard input, run mongorestore
with the —archive
option but _omit_the filename. For example:
- mongodump --archive --db=test --port=27017 | mongorestore --archive --port=27018