Database Reference
In-Depth Information
10.3
Maintenance
Here I'll describe the three most common MongoDB maintenance tasks. First, I'll dis-
cuss backups. As with any database, prudence dictates a regular backup policy. Then,
I'll describe compaction, as the data files may require it under rare circumstances.
Finally, I'll briefly mention upgrades, as you'll want to run the latest stable MongoDB
release when possible.
10.3.1
Backups and recovery
Part of running a production database deployment is being prepared for disasters.
Backups play an important role in this. When disaster strikes, a good backup can save
the day, and in these cases, you'll never regret having invested time and diligence in a
regular backup policy. Yet some users still decide that they can live without backups.
These users have only themselves to blame when they can't recover their databases.
Don't be one of these users.
There are two general strategies for backing up a MongoDB database. The first is
to use the mongodump and mongorestore utilities. The second, and probably the more
common, is to copy the raw data files.
MONGODUMP AND MONGORESTORE
mongodump writes the contents of a database as BSON files. mongorestore reads these
files and restores them. These tools are useful for backing up individual collections
and databases as well as the whole server. They can be run against a live server (you
don't have to lock or shut down the server) or you can point them to a set of data files,
but only when the server is locked or shut down. The simplest way to run mongodump is
like so:
$ mongodump -h localhost --port 27017
This will dump each database and collection from the server at localhost to a directory
called dump . The dump will include all the documents from each collection, including
the system collections that define users and indexes. But significantly, the indexes
themselves won't be included in the dump. The means that when you restore, any
indexes will have to be rebuilt. If you have an especially large data set, or a large num-
ber of indexes, this will take time.
To restore BSON files, run mongorestore , and point it at the dump folder:
$ mongorestore -h localhost --port 27017 dump
Note that when restoring, mongorestore won't drop data by default. So if you're
restoring to an existing database, be sure to run with the --drop flag.
D ATAFILE - BASED BACKUPS
Most users opt for a file-based backup, where the raw data files are copied to a new
location. This approach is often faster than mongodump , since the backups and restora-
tions require no transformation of the data. 9 The only potential problem with a file-
9
As an example, this strategy preserves all indexes—no need to rebuild them on restore.
Search WWH ::




Custom Search