Docs Home → MongoDB Database Tools
mongorestore

On this page
Synopsis
The mongorestore
program loads data from either a binary
database dump created by mongodump
or the standard input
into a mongod
or mongos
instance.
Run mongorestore
from the system command line, not the mongo
shell.
Tip
See also:
mongodump
which provides the corresponding
binary data export capability.
You can use mongorestore
to migrate from a self-hosted deployment
to MongoDB Atlas. MongoDB
Atlas is the fully managed service for MongoDB deployments in the
cloud. To learn more, see Seed with mongorestore.
To learn all the ways you can migrate to MongoDB Atlas, see
Migrate or Import Data.
Versioning
This documentation is for version 100.9.0
of mongorestore
.
Compatibility
MongoDB Server Compatibility
mongorestore
version 100.9.0
supports the following versions
of the MongoDB Server:
MongoDB 7.0
MongoDB 6.0
MongoDB 5.0
MongoDB 4.4
MongoDB 4.2
While mongorestore
may work on earlier versions of MongoDB server,
any such compatibility is not guaranteed.
Platform Support
mongorestore
version 100.9.0
is supported on the following
platforms:
x86_64 | ARM64 | PPC64LE | s390x | |
---|---|---|---|---|
Amazon Linux 2023 | ✓ | ✓ | ||
Amazon 2 | ✓ | |||
Amazon 2013.03+ | ✓ | |||
Debian 10 | ✓ | |||
Debian 9 | ✓ | |||
Debian 8 | ✓ | |||
RHEL / CentOS 9 | ✓ | ✓ | ||
RHEL / CentOS 8 | ✓ | ✓ | ||
RHEL / CentOS 7 | ✓ | ✓ | ✓ | |
RHEL / CentOS 6 | ✓ | |||
SUSE 15 | ✓ | |||
SUSE 12 | ✓ | |||
Ubuntu 20.04 | ✓ | ✓ | ||
Ubuntu 18.04 | ✓ | ✓ | ||
Ubuntu 16.04 | ✓ | ✓ | ✓ | |
Windows 8 and later | ✓ | |||
Windows Server 2012 and later | ✓ | |||
macOS 11 and later | ✓ | ✓ | ||
macOS 10.12 - 10.15 | ✓ |
Additional Considerations for Ubuntu 18.04
Ubuntu 18.04 may use a non-standard DNS resolver. When you use a
non-standard DNS resolver, mongorestore
returns an error message like:
error parsing uri: lookup <HOSTNAME> on 127.0.0.53:53: cannot unmarshal DNS message
To resolve the problem, edit /etc/resolv.conf
to point to a
different DNS resolver.
Installation
The mongorestore
tool is part of the MongoDB Database Tools package:
➤ Follow the Database Tools Installation Guide to install mongorestore
.
Syntax
The mongorestore
command has the following syntax:
mongorestore <options> <connection-string> <directory or file to restore>
Run mongorestore
from the system command line, not the mongo
shell.
For example, to restore from a dump
directory to a local
mongod
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 the
dump/
directory. For example, the following operation restores a
single collection from corresponding data files in the dump/
directory:
mongorestore --nsInclude=test.purchaseorders dump/
If the dump/
directory does not contain the corresponding data file
for the specified namespace, no data will be restored. For example, the
following specifies a collection namespace that does not have a
corresponding 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, see Options.
Behavior
Restore to Matching Server Version
When using mongorestore
to load data files created by
mongodump
, the MongoDB versions of your source and
destination deployments must be either:
The same major version.
The same feature compatibility version.
For example, if your dump was created from a MongoDB deployment running
version 4.4
, the MongoDB deployment you restore to must also run
version 4.4
or have its FCV set to 4.4
.
To change your feature compatibility version, see
setFeatureCompatibilityVersion
.
Note
You can restore the BSON files generated from mongodump
into MongoDB deployments running the same or newer version
as the source deployment.
This guarantee does not apply to metadata, archive, or oplog replay
files. If you try to restore these files using different
source and destination deployment versions, the mongorestore
process could result in failure, silent failure, or corrupted
metadata.
In addition, ensure that you are using the same version of
mongorestore
to load the data files as the version of
mongodump
that you used to create them. For example, if
you used mongodump
version 100.9.0
to create the
dump, use mongorestore
version 100.9.0
to restore
it.
Insert Only
mongorestore
can create a new database or add data to an
existing database. However, mongorestore
performs inserts
only and does not perform updates. That is, if restoring documents to
an existing database and collection and existing documents have the
same value _id
field as the to-be-restored documents,
mongorestore
will not overwrite those documents.
Rebuild Indexes
mongorestore
recreates indexes recorded by
mongodump
after restoring data.
Note
For MongoDB installations with featureCompatibilityVersion
(fCV)
set to "4.0"
or earlier, creating indexes will
error if an index key in an existing document exceeds the
limit.
To avoid this issue, consider using hashed indexes or indexing a
computed value instead. If you want to resolve the index issue after
restoring the data, you can disable the default index key length
validation on the target database by setting the mongod
instance's failIndexKeyTooLong
parameter to false.
Exclude system.profile
Collection
mongorestore
does not restore the system.profile
collection data.
FIPS
mongorestore
automatically creates FIPS-compliant
connections to a mongod
/mongos
that is
configured to use FIPS mode.
Write Concern
If you specify write concern in both the
--writeConcern
option and the
--uri
connection string option, the
--writeConcern
value overrides
the write concern specified in the URI string.
Time Series Collections
Starting in MongoDB 5.0, you can use mongorestore
to restore
timeseries collections.
For details, see Restore a Time Series Collection.
Required Access
To restore data to a MongoDB deployment that has access control enabled, the restore
role provides
the necessary privileges to restore data from backups if the data does
not 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
mongorestore
with the
--oplogReplay
option, you need
additional privileges:
system.profile | If the backup data includes Both the built-in roles |
--oplogReplay | To run with Grant only to users who must run |
Usage in Backup Strategy
Standalones/Replica Sets
For an overview of mongorestore
usage as part of a
backup and recovery strategy, see
Back Up and Restore with MongoDB Tools.
Sharded Clusters
mongodump
and mongorestore
cannot be part of a backup strategy for 4.2+ sharded clusters
that have sharded transactions in progress, as backups created with
mongodump
do not maintain the atomicity guarantees
of transactions across shards.
For 4.2+ sharded clusters with in-progress sharded transactions, use one of the following coordinated backup and restore processes which do maintain the atomicity guarantees of transactions across shards:
Options
--verbose, -v
Increases the amount of internal reporting returned on standard output or in log files. Increase the verbosity with the
-v
form by including the option multiple times, (e.g.-vvvvv
.)
--quiet
Runs
mongorestore
in a quiet mode that attempts to limit the amount of output.This option suppresses:
output from database commands
replication activity
connection accepted events
connection closed events
--config=<filename>
New in version 100.3.0.
Specifies the full path to a YAML configuration file containing sensitive values for the following options to
mongorestore
:This is the recommended way to specify a password to
mongorestore
, aside from specifying it through a password prompt.The configuration file takes the following form:
password: <password> uri: mongodb://mongodb0.example.com:27017 sslPEMKeyPassword: <password> Specifying a password to the
password:
field and providing a connection string in theuri:
field which contains a conflicting password will result in an error.Be sure to secure this file with appropriate filesystem permissions.
Note
If you specify a configuration file with
--config
and also use the--password
,--uri
or--sslPEMKeyPassword
option tomongorestore
, each command line option overrides its corresponding option in the configuration file.
--uri=<connectionString>
Specifies the resolvable URI connection string of the MongoDB deployment, enclosed in quotes:
--uri="mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]" Starting with version
100.0
ofmongorestore
, the connection string may alternatively be provided as a positional parameter, without using the--uri
option:mongorestore mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] As a positional parameter, the connection string may be specified at any point on the command line, as long as it begins with either
mongodb://
ormongodb+srv://
. For example:mongorestore --username joe --password secret1 mongodb://mongodb0.example.com:27017 --ssl Only one connection string can be provided. Attempting to include more than one, whether using the
--uri
option or as a positional argument, will result in an error.For information on the components of the connection string, see the Connection String URI Format documentation.
Note
Some components in the
connection string
may alternatively be specified using their own explicit command-line options, such as--username
and--password
. Providing a connection string while also using an explicit option and specifying conflicting information will result in an error.Note
If using
mongorestore
on Ubuntu 18.04, you may experience acannot unmarshal DNS
error message when using SRV connection strings (in the formmongodb+srv://
) with the--uri
option. If so, use one of the following options instead:the
--uri
option with a non-SRV connection string (in the formmongodb://
)the
--host
option to specify the host to connect to directly
Warning
On some systems, a password provided in a connection string with the
--uri
option may be visible to system status programs such asps
that may be invoked by other users. Consider instead:omitting the password in the connection string to receive an interactive password prompt, or
using the
--config
option to specify a configuration file containing the password.
--host=<hostname><:port>, -h=<hostname><:port>
Default: localhost:27017
Specifies the resolvable hostname of the MongoDB deployment. By default,
mongorestore
attempts to connect to a MongoDB instance running on the localhost on port number27017
.To connect to a replica set, specify the
replSetName
and a seed list of set members, as in the following:--host=<replSetName>/<hostname1><:port>,<hostname2><:port>,<...> When specifying the replica set list format,
mongorestore
always connects to the primary.You can also connect to any single member of the replica set by specifying the host and port of only that member:
--host=<hostname1><:port> If you use IPv6 and use the
<address>:<port>
format, you must enclose the portion of an address and port combination in brackets (e.g.[<address>]
).Alternatively, you can also specify the hostname directly in the
URI connection string
. Providing a connection string while also using--host
and specifying conflicting information will result in an error.
--port=<port>
Default: 27017
Specifies the TCP port on which the MongoDB instance listens for client connections.
Alternatively, you can also specify the port directly in the
URI connection string
. Providing a connection string while also using--port
and specifying conflicting information will result in an error.
--ssl
Enables connection to a
mongod
ormongos
that has TLS/SSL support enabled.Alternatively, you can also configure TLS/SSL support directly in the
URI connection string
. Providing a connection string while also using--ssl
and specifying conflicting information will result in an error.For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.
--sslCAFile=<filename>
Specifies the
.pem
file that contains the root certificate chain from the Certificate Authority. Specify the file name of the.pem
file using relative or absolute paths.Alternatively, you can also specify the
.pem
file directly in theURI connection string
. Providing a connection string while also using--sslCAFile
and specifying conflicting information will result in an error.For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.
--sslPEMKeyFile=<filename>
Specifies the
.pem
file that contains both the TLS/SSL certificate and key. Specify the file name of the.pem
file using relative or absolute paths.This option is required when using the
--ssl
option to connect to amongod
ormongos
that hasCAFile
enabled withoutallowConnectionsWithoutCertificates
.Alternatively, you can also specify the
.pem
file directly in theURI connection string
. Providing a connection string while also using--sslPEMKeyFile
and specifying conflicting information will result in an error.For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.
--sslPEMKeyPassword=<value>
Specifies the password to de-crypt the certificate-key file (i.e.
--sslPEMKeyFile
). Use the--sslPEMKeyPassword
option only if the certificate-key file is encrypted. In all cases, themongorestore
will redact the password from all logging and reporting output.If the private key in the PEM file is encrypted and you do not specify the
--sslPEMKeyPassword
option, themongorestore
will prompt for a passphrase. See TLS/SSL Certificate Passphrase.Alternatively, you can also specify the password directly in the
URI connection string
. Providing a connection string while also using--sslPEMKeyPassword
and specifying conflicting information will result in an error.For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.
Warning
On some systems, a password provided directly using the
--sslPEMKeyPassword
option may be visible to system status programs such asps
that may be invoked by other users. Consider using the--config
option to specify a configuration file containing the password instead.
--sslCRLFile=<filename>
Specifies the
.pem
file that contains the Certificate Revocation List. Specify the file name of the.pem
file using relative or absolute paths.For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.
--sslAllowInvalidCertificates
Bypasses the validation checks for server certificates and allows the use of invalid certificates. When using the
allowInvalidCertificates
setting, MongoDB logs as a warning the use of the invalid certificate.Warning
Although available, avoid using the
--sslAllowInvalidCertificates
option if possible. If the use of--sslAllowInvalidCertificates
is necessary, only use the option on systems where intrusion is not possible.Connecting to a
mongod
ormongos
instance without validating server certificates is a potential security risk. If you only need to disable the validation of the hostname in the TLS/SSL certificates, see--sslAllowInvalidHostnames
.Alternatively, you can also disable certificate validation directly in the
URI connection string
. Providing a connection string while also using--sslAllowInvalidCertificates
and specifying conflicting information will result in an error.For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.
--sslAllowInvalidHostnames
Disables the validation of the hostnames in TLS/SSL certificates. Allows
mongorestore
to connect to MongoDB instances even if the hostname in their certificates do not match the specified hostname.Alternatively, you can also disable hostname validation directly in the
URI connection string
. Providing a connection string while also using--sslAllowInvalidHostnames
and specifying conflicting information will result in an error.For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.
--username=<username>, -u=<username>
Specifies a username with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the
--password
and--authenticationDatabase
options.Alternatively, you can also specify the username directly in the
URI connection string
. Providing a connection string while also using--username
and specifying conflicting information will result in an error.If connecting to a MongoDB Atlas cluster using the
MONGODB-AWS
authentication mechanism
, you can specify your AWS access key ID in:this field,
the
connection string
, orthe
AWS_ACCESS_KEY_ID
environment variable.
See Connect to a MongoDB Atlas Cluster using AWS IAM Credentials for an example of each.
--password=<password>, -p=<password>
Specifies a password with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the
--username
and--authenticationDatabase
options.To prompt the user for the password, pass the
--username
option without--password
or specify an empty string as the--password
value, as in--password=""
.Alternatively, you can also specify the password directly in the
URI connection string
. Providing a connection string while also using--password
and specifying conflicting information will result in an error.If connecting to a MongoDB Atlas cluster using the
MONGODB-AWS
authentication mechanism
, you can specify your AWS secret access key in:this field,
the
connection string
, orthe
AWS_SECRET_ACCESS_KEY
environment variable.
See Connect to a MongoDB Atlas Cluster using AWS IAM Credentials for an example of each.
Warning
On some systems, a password provided directly using the
--password
option may be visible to system status programs such asps
that may be invoked by other users. Consider instead:omitting the
--password
option to receive an interactive password prompt, orusing the
--config
option to specify a configuration file containing the password.
--awsSessionToken=<AWS Session Token>
If connecting to a MongoDB Atlas cluster using the
MONGODB-AWS
authentication mechanism
, and using session tokens in addition to your AWS access key ID and secret access key, you can specify your AWS session token in:this field,
the
AWS_SESSION_TOKEN
authMechanismProperties
parameter to theconnection string
, orthe
AWS_SESSION_TOKEN
environment variable.
See Connect to a MongoDB Atlas Cluster using AWS IAM Credentials for an example of each.
Only valid when using the
MONGODB-AWS
authentication mechanism
.
--authenticationDatabase=<dbname>
Specifies the authentication database where the specified
--username
has been created. See Authentication Database.If using the GSSAPI (Kerberos), PLAIN (LDAP SASL), or
MONGODB-AWS
authentication mechanisms
, you must set--authenticationDatabase
to$external
.Alternatively, you can also specify the authentication database directly in the
URI connection string
. Providing a connection string while also using--authenticationDatabase
and specifying conflicting information will result in an error.
--authenticationMechanism=<name>
Default: SCRAM-SHA-1
Specifies the authentication mechanism the
mongorestore
instance uses to authenticate to themongod
ormongos
.Changed in version 100.1.0: Starting in version
100.1.0
,mongorestore
adds support for theMONGODB-AWS
authentication mechanism when connecting to a MongoDB Atlas cluster.ValueDescriptionRFC 5802 standard Salted Challenge Response Authentication Mechanism using the SHA-1 hash function.RFC 7677 standard Salted Challenge Response Authentication Mechanism using the SHA-256 hash function.
Requires featureCompatibilityVersion set to
4.0
.MongoDB TLS/SSL certificate authentication.MONGODB-AWS
External authentication using AWS IAM credentials for use in connecting to a MongoDB Atlas cluster. See Connect to a MongoDB Atlas Cluster using AWS IAM Credentials.
New in version 100.1.0.
GSSAPI (Kerberos)External authentication using Kerberos. This mechanism is available only in MongoDB Enterprise.PLAIN (LDAP SASL)External authentication using LDAP. You can also usePLAIN
for authenticating in-database users.PLAIN
transmits passwords in plain text. This mechanism is available only in MongoDB Enterprise.Alternatively, you can also specify the authentication mechanism directly in the
URI connection string
. Providing a connection string while also using--authenticationMechanism
and specifying conflicting information will result in an error.
--gssapiServiceName=<serviceName>
Specify the name of the service using GSSAPI/Kerberos. Only required if the service does not use the default name of
mongodb
.This option is available only in MongoDB Enterprise.
--gssapiHostName=<hostname>
Specify the hostname of a service using GSSAPI/Kerberos. Only required if the hostname of a machine does not 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 data into when restoring from a BSON file. If the database does not exist,mongorestore
creates the database. For example, the following example restores thesalaries
collection into thereporting
database.mongorestore --db=reporting dump/test/salaries.bson If you do not specify
--db
,mongorestore
reads the database name from the data files.The use of
--db
and--collection
options are deprecated when restoring from a directory or an archive file. Instead, to restore from an archive or a directory, see--nsInclude
instead.Alternatively, you can also specify the database directly in the
URI connection string
. Providing a connection string while also using--db
and specifying conflicting information will result in an error.
--collection=<collection>, -c=<collection>
Specifies the name of the destination collection for
mongorestore
to restore data into when restoring from a BSON file. If you do not specify--collection
,mongorestore
takes the collection name from the input filename. If the input file has an extension, MongoDB omits the extension of the file from the collection name.mongorestore --db=reporting --collection=employeesalaries dump/test/salaries.bson The use of
--db
and--collection
options are deprecated when restoring from a directory or an archive file. Instead, to restore from an archive or a directory, see--nsInclude
instead.
--nsExclude=<namespace pattern>
Specifies a namespace pattern (e.g.
"test.myCollection"
,"reporting.*"
,"dept*.bar"
) to exclude the matching namespaces from the restore. In the pattern, you can use asterisks*
as wild cards. For an example of the wildcard pattern, see Restore Collections Using Wild Cards.You can specify
--nsExclude
multiple times to exclude multiple namespace patterns.
--nsInclude=<namespace pattern>
Specifies a namespace pattern (e.g.
"test.myCollection"
,"reporting.*"
,"dept*.bar"
) to restore only the namespaces that match the pattern. In the pattern, you can use asterisks*
as wild cards. For an example of the wildcard pattern, see Restore Collections Using Wild Cards.You can specify
--nsInclude
multiple times to include multiple namespace patterns.If source directory or file (i.e. the directory/file from which you are restoring the data) does not contain data files that match the namespace pattern, no data will be restored.
For collection names that contain non-ascii characters,
mongodump
outputs the corresponding filenames with percent-encoded names. However, to restore these collections, do not use the encoded names. Instead, use the namespace with the non-ascii characters.For example, if the dump directory contains
dump/test/caf%C3%A9s.bson
, specify--nsInclude "test.cafés"
.
--nsFrom=<namespace pattern>
Use with
--nsTo
to rename a namespace during the restore operation.--nsFrom
specifies the collection in the dump file, while--nsTo
specifies the name that should be used in the restored database.--nsFrom
accepts a namespace pattern as its argument. The namespace pattern permits--nsFrom
to refer to any namespace that matches the specified pattern.mongorestore
matches the smallest valid occurence of 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 the first asterisk in--nsFrom
matches the first asterisk innsTo
.For more complex replacements, use dollar signs to delimit a "wild card" variable to use in the replacement. Change Collection Namespaces during Restore provides an example of complex replacements with dollar sign-delimited wild cards.
Unlike replacements with asterisks, replacements with dollar sign-delimited wild cards do not need to be linear.
--nsTo=<namespace pattern>
Use with
--nsFrom
to rename a namespace during the restore operation.--nsTo
specifies the new collection name to use in the restored database, while--nsFrom
specifies the name in the dump file.--nsTo
accepts a namespace pattern as its argument. The namespace pattern permits--nsTo
to refer to any namespace that matches the specified pattern.mongorestore
matches the smallest valid occurence of 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 the first asterisk in--nsFrom
matches the first asterisk innsTo
.For more complex replacements, use dollar signs to delimit a "wild card" variable to use in the replacement. Change Collection Namespaces during Restore provides an example of complex replacements with dollar sign-delimited wild cards.
Unlike replacements with asterisks, replacements with dollar sign-delimited wild cards do not need to be linear.
--objcheck
Forces
mongorestore
to validate all requests from clients upon receipt to ensure that clients never insert invalid documents into the 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 the collections from the target database.
--drop
does not drop collections that are not in the backup.When the restore includes the
admin
database,mongorestore
with--drop
removes all user credentials and replaces them with the users defined in the dump file. Therefore, in systems withauthorization
enabled,mongorestore
must be able to authenticate to an existing user and to a user defined in the dump file. Ifmongorestore
can't authenticate to a user defined in the dump file, the restoration process will fail, leaving an empty database.If a collection is dropped and recreated as part of the restore, the newly created collection has a different UUID unless
--drop
is used with--preserveUUID
.
--preserveUUID
Restored collections use the UUID from the restore data instead of creating a new UUID for collections that are dropped and recreated as part of the restore.
To use
--preserveUUID
, you must also include the--drop
option.
--dryRun
Runs
mongorestore
without actually importing any data, returning themongorestore
summary information. Use with--verbose
to produce more detailed summary information.
--oplogReplay
After restoring the database dump, replays the oplog entries from 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 file in the following locations:The top level of the dump directory, as in the case of a dump created with
mongodump --oplog
.The path specified by
--oplogFile
.<dump-directory>/local/oplog.rs.bson
, as in the case of a dump of theoplog.rs
collection in thelocal
database on amongod
that is a member of a replica set.
If there is an
oplog.bson
file at the top level of the dump directory 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 bson files in thedump/local
directory,mongorestore
restores them like normal collections.If you specify an oplog file using
--oplogFile
,mongorestore
restores that file as the oplog. If there are also bson files in thedump/local
directory,mongorestore
restores them like normal collections.The following message in the oplog replay output shows the number of inserts before the oplog replay. It does not include inserts performed during the replay.
0 document(s) restored successfully. 0 document(s) failed to restore. For an example of
--oplogReplay
, see Restore Point in Time Oplog Backup.Note
When using
mongorestore
with--oplogReplay
to restore a replica set, you must restore a full dump of a replica set member created usingmongodump --oplog
.mongorestore
with--oplogReplay
fails if you use any of the following options to limit the data to be restored:Tip
--oplogLimit=<timestamp>
Prevents
mongorestore
from applying oplog entries with 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 the specified second.You must use
--oplogLimit
in conjunction with the--oplogReplay
option.
--oplogFile=<path>
Specifies the path to the oplog file containing oplog data for the restore. Use with
--oplogReplay
.If you specify
--oplogFile
and there is anoplog.bson
file at the top level of the dump directory,mongorestore
returns an error.
--convertLegacyIndexes
New in version 100.0.0.
Removes any invalid index options specified in the corresponding
mongodump
output, and rewrites any legacy index key values to use valid values.Invalid index options are any options specified to an index that are not listed as a valid field for the
createIndexes
command. For example,name
andcollation
are valid, but an arbitrarycustom_field
is not. With--convertLegacyIndexes
specified, any invalid index options found are dropped.Legacy index key values are any values for index type that are no longer supported. For example,
1
and-1
are valid index key values, but0
or an empty string are legacy values. With--convertLegacyIndexes
specified, any legacy index key values found are rewritten as1
. Non-empty string values are not replaced.
Without the
--convertLegacyIndexes
option specified, the presence of invalid index options or legacy index key values could cause the index build to fail.If the
--noIndexRestore
option is specified tomongorestore
, the--convertLegacyIndexes
option is ignored.
--keepIndexVersion
Prevents
mongorestore
from upgrading the index to the latest version during the restoration process.
--noIndexRestore
Prevents
mongorestore
from restoring and building indexes as specified in the correspondingmongodump
output.
--noOptionsRestore
Prevents
mongorestore
from setting the collection options, such as those specified by thecollMod
database command, on restored collections.
--restoreDbUsersAndRoles
Restore user and role definitions for the given database. See system.roles Collection and system.users Collection for more information.
Note
The
--restoreDbUsersAndRoles
option cannot be used if specifying theadmin
database to the--db
option, and attempting to do so will result in an error. Restoring theadmin
database by specifying--db admin
tomongorestore
already restores all users and roles.
--writeConcern=<document>
Default: majority
Specifies the write concern for each write operation that
mongorestore
performs.Specify the write concern as a document with w options:
--writeConcern="{w:'majority'}" If the write concern is also included in the
--uri connection string
, the command-line--writeConcern
overrides the write concern specified in the URI string.
--maintainInsertionOrder
Default: false
If specified,
mongorestore
inserts the documents in the order of their appearance in the input source. That is, both the bulk write batch order and document order within the batches are maintained.Specifying
--maintainInsertionOrder
also enables--stopOnError
and setsnumInsertionWorkersPerCollection
to 1.If unspecified,
mongorestore
may perform the insertions in an arbitrary order.
--numParallelCollections=<int>, -j=<int>
Default: 4
Number of collections
mongorestore
should restore in parallel.If you specify
-j
when restoring a single collection,-j
maps to the--numInsertionWorkersPerCollection
option rather than--numParallelCollections
.
--numInsertionWorkersPerCollection=<int>
Default: 1
Specifies the number of insertion workers to run concurrently per collection.
For large imports, increasing the number of insertion workers may increase the speed of the import.
--stopOnError
Forces
mongorestore
to halt the restore when it encounters an error.By default,
mongorestore
continues when it encounters duplicate key and document validation errors. To ensure that the program stops on these errors, specify--stopOnError
.
--bypassDocumentValidation
Enables
mongorestore
to bypass document validation during the operation. This lets you insert documents that do not meet the validation requirements. This option is required if you are restoring a Queryable Encryption enabled collection.
--gzip
Restores from compressed files or data stream created by
mongodump --gzip
To restore from a dump directory that contains compressed files, run
mongorestore
with the--gzip
option.To restore from a compressed archive file, run
mongorestore
with both the--gzip
and the--archive
options.
--archive=<file>
Restores from the specified archive file or, if the file is unspecified, from the standard input (
stdin
):To restore from an archive file, run
mongorestore
with the--archive
option and the archive filenameTo restore from the standard input, run
mongorestore
with the--archive
option but omit the filename.
Examples
Run mongorestore
from the system command line, not the mongo
shell.
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 host
mongodb1.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, and
authentication 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
To restore a specific collection, use --nsInclude
, passing in the full namespace
(<database>.<collection>
) of the collection.
For example, the following restores the collection named
purchaseorders
in the database test
from the corresponding
files located in the dump/
directory.
mongorestore --nsInclude=test.purchaseorders dump/
The mongorestore
outputs the results, including the
number 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 data
files 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 a Queryable Encryption Enabled Collection
Queryable Encryption adds a __safeContent__
field to documents in an encrypted
collection and blocks insert and update operations on those
documents unless document validation is disabled. To restore a
collection that includes encrypted fields, use
--bypassDocumentValidation
.
mongodump
exports a Queryable Encryption enabled collection's
associated metadata collections. Running mongorestore
restores these collections as well.
mongorestore --db=test --collection=personaldata dump/test/personaldata.bson --bypassDocumentValidation
Restore Collections Using Wild Cards
--nsInclude
and
--nsExclude
support specifying the
namespaces you wish to include or exclude from a
restore operation using asterisks as wild cards.
The following example restores the documents in the dump/
sub-directory of the current directory that match the specified
namespace pattern. The --nsInclude
statement specifies to only restore documents in the transactions
database while --nsExclude
instructs mongorestore
to exclude collections whose
names end with _dev
. mongorestore
restores data to
the mongod
instance running on the localhost interface
on port 27017
.
mongorestore --nsInclude='transactions.*' --nsExclude='transactions.*_dev' dump/
Change Collection Namespaces during Restore
You can use the --nsFrom
and
--nsTo
options to change the namespace
of the 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 in
the replacement.
Consider a database data
that you have exported to a dump/
directory using mongodump
. The data
database
contains 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 different
namespaces. The following operation
restores the
sales_<customerName>
collections in thedata
database tosales
collections in the<customerName>
database, andrestores 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
and
mongorestore
(with the mongorestore
options
--nsFrom
and --nsTo
).
For example, to copy the test
database from a local instance
running on the default port 27017 to the examples
database on the
same instance, you can:
Use
mongodump
to dump thetest
database to an archivemongodump-test-db
:mongodump --archive="mongodump-test-db" --db=test Use
mongorestore
with--nsFrom
and--nsTo
to restore (with database name change) from the archive:mongorestore --archive="mongodump-test-db" --nsFrom='test.*' --nsTo='examples.*'
Tip
Include additional options as necessary, such as to specify the uri or host, username, password and authentication database.
Alternatively, instead of using an archive file, you can
mongodump
the test
database to the standard
output 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 mongorestore
with the new
--archive
option and the archive filename.
mongorestore --archive=test.20150715.archive
Restore a Database from an Archive File
To restore from an archive file, run mongorestore
with the new
--archive
option and the archive filename. For example, the
following operation restores the test
database from the file
test.20150715.archive
.
mongorestore --archive=test.20150715.archive --nsInclude="test.*"
Restore from Compressed Data
mongorestore
can restore from compressed files or
compressed archive files created by mongodump
.
To restore from a dump directory that contains compressed files, run
mongorestore
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, run
mongorestore
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
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
Restore a Time Series Collection
Use mongosh
to create a time series collection. This example
uses the default test
database:
db.createCollection( "weather", { timeseries: { timeField: "timestamp", metaField: "metadata", granularity: "hours" } } )
Insert time series documents into the collection:
db.weather.insertMany( [ { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-18T00:00:00.000Z"), "temp": 12 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-18T04:00:00.000Z"), "temp": 11 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-18T08:00:00.000Z"), "temp": 11 } ] )
From your terminal, use mongodump
to export the time series collection
to the dump/test
directory. This commands adds
system.buckets.weather.bson
and weather.metadata.json
to
the directory:
mongodump --db=test
Use mongorestore
to restore the data to the mongorestore.weather
namespace:
mongorestore --host localhost --port 27017 --nsFrom='test.*' --nsTo='mongorestore.*' dump/
Note
You cannot restore the system.buckets.weather.bson
file
by itself. Attempting to do so results in an error.
Connect to a MongoDB Atlas Cluster using AWS IAM Credentials
New in version 100.1.0.
To connect to a MongoDB Atlas cluster which
has been configured to support authentication via AWS IAM credentials,
provide a connection string
to
mongorestore
similar to the following:
mongorestore 'mongodb+srv://<aws access key id>:<aws secret access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS' <other options>
Connecting to Atlas using AWS IAM credentials in this manner uses the
MONGODB-AWS
authentication mechanism
and the $external
authSource
, as shown in this example.
If using an AWS session token,
as well, provide it with the AWS_SESSION_TOKEN
authMechanismProperties
value, as follows:
mongorestore 'mongodb+srv://<aws access key id>:<aws secret access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<aws session token>' <other options>
Note
If the AWS access key ID, secret access key, or session token include the following characters:
: / ? # [ ] @
those characters must be converted using percent encoding.
Alternatively, the AWS access key ID, secret access key, and optionally
session token can each be provided outside of the connection string
using the --username
, --password
, and
--awsSessionToken
options instead, like so:
mongorestore 'mongodb+srv://cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS' --username <aws access key id> --password <aws secret access key> --awsSessionToken <aws session token> <other options>
When provided as command line parameters, these three options do not require percent encoding.
You may also set these credentials on your platform using standard
AWS IAM environment variables.
mongorestore
checks for the following environment variables when you
use the MONGODB-AWS
authentication mechanism
:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
AWS_SESSION_TOKEN
If set, these credentials do not need to be specified in the connection string or via their explicit options.
Note
If you chose to use the AWS environment variables to specify these values, you cannot mix and match with the corresponding explicit or connection string options for these credentials. Either use the environment variables for access key ID and secret access key (and session token if used), or specify each of these using the explicit or connection string options instead.
The following example sets these environment variables in the bash
shell:
export AWS_ACCESS_KEY_ID='<aws access key id>' export AWS_SECRET_ACCESS_KEY='<aws secret access key>' export AWS_SESSION_TOKEN='<aws session token>'
Syntax for setting environment variables in other shells will be different. Consult the documentation for your platform for more information.
You can verify that these environment variables have been set with the following command:
env | grep AWS
Once set, the following example connects to a MongoDB Atlas cluster using these environment variables:
mongorestore 'mongodb+srv://cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS' <other options>