MongoDB: Recover Data after an Unexpected Shutdown in Ubuntu

If you try to run mongod but it fails to start and have this error in the log file (/var/log/mongodb/mongodb.log) you’ll have to repair your db.

************** 
Unclean shutdown detected.
Please visit http://dochub.mongodb.org/core/repair for recovery instructions.
*************
Thu Dec  5 14:42:47.209 [initandlisten] exception in initAndListen: 12596 old lock file, terminating
Thu Dec  5 14:42:47.209 dbexit: 
Thu Dec  5 14:42:47.209 [initandlisten] shutdown: going to close listening sockets...
Thu Dec  5 14:42:47.209 [initandlisten] shutdown: going to flush diaglog...
Thu Dec  5 14:42:47.209 [initandlisten] shutdown: going to close sockets...
Thu Dec  5 14:42:47.209 [initandlisten] shutdown: waiting for fs preallocator...
Thu Dec  5 14:42:47.209 [initandlisten] shutdown: closing all files...
Thu Dec  5 14:42:47.209 [initandlisten] closeAllFiles() finished
Thu Dec  5 14:42:47.209 dbexit: really exiting now

Note: MongoDBs data files are usually located at /data/db but in my Ubuntu installation they where in /var/lib/mongodb.

mongodb-logo

Repair preserving data:

sudo mkdir /var/lib/mongodb0
sudo mongod --dbpath /var/lib/mongodb --repair --repairpath /var/lib/mongodb0
sudo mongod --dbpath /var/lib/mongodb0

Now that the server is up with a repaired version (/var/lib/mongodb0) of your original data (from /var/lib/mongodb) use mongo client to verify that everything is OK. In that case replace /var/lib/mongodb with /var/lib/mongodb0.

sudo rm -rf /var/lib/mongodb
sudo mv /var/lib/mongodb0 /var/lib/mongodb
sudo chown -R mongodb:mongodb /var/lib/mongodb

Repair without preserving data:

sudo rm /var/lib/mongodb/mongod.lock
sudo mongod --dbpath /var/lib/mongodb --repair

When this completes, the repaired data files will replace the original data files in the /var/lib/mongodb directory.

Ref: http://docs.mongodb.org/manual/tutorial/recover-data-following-unexpected-shutdown/

You might also like

Install MongoDB and the PHP driver in CentOS
Install MongoDB serverCreate the /etc/yum.repos.d/mongodb-org-3.0.repo file with this content:name=MongoDB...

Install MongoDB in Ubuntu 12.04 with PHP driver
Install MongoDB:sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 echo...

Install and configure MongoDB and PHP driver with MacPorts
Installing and configuring MongoDB with MacPortsInstalling MongoDB with MacPorts is as easy as...

Solve “mongodb cannot be built while v8 is active” in MacPorts
While updating all the ports of macports I got this error:---> Configuring mongodb Error: mongodb...

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.