Databases Reference
In-Depth Information
Along with
mongodump
, MongoDB distributions include a corresponding tool for re-
storing data from a backup,
mongorestore
.
mongorestore
takes the output from running
mongodump
and inserts the backed-up data into a running instance of MongoDB. The
following example session shows a hot backup of the database
test
to the
backup
di-
rectory, followed by a separate call to
mongorestore
:
$ ./mongodump -d test -o backup
connected to: 127.0.0.1
DATABASE: test to backup/test
test.x to backup/test/x.bson
1 objects
$ ./mongorestore -d foo --drop backup/test/
connected to: 127.0.0.1
backup/test/x.bson
going into namespace [foo.x]
dropping
1 objects
In the previous example, we use
-d
to specify a database to restore to, in this case
foo
.
This option allows us to restore a backup to a database with a different name than the
original. We also use the
--drop
option, which will drop the collection (if it exists)
before restoring data to it. Otherwise, the data will be merged into any existing collec-
tion, possibly overwriting some documents. Again, for a complete list of options, run
mongorestore --help
.
fsync and Lock
Although
mongodump
and
mongorestore
allow us to take backups without shutting down
the MongoDB server, we lose the ability to get a point-in-time view of the data.
MongoDB's
fsync
command allows us to copy the data directory of a running
MongoDB server without risking any corruption.
The
fsync
command will force the MongoDB server to flush all pending writes to disk.
It will also, optionally, hold a lock preventing any further writes to the database until
the server is unlocked. This write lock is what allows the
fsync
command to be useful
for backups. Here is an example of how to run the command from the shell, forcing an
fsync
and acquiring a write lock:
> use admin
switched to db admin
> db.runCommand({"fsync" : 1, "lock" : 1});
{
"info" : "now locked against writes, use db.$cmd.sys.unlock.findOne() to unlock",
"ok" : 1
}
At this point, the data directory represents a consistent, point-in-time snapshot of our
data. Because the server is locked for writes, we can safely make a copy of the data