Sunday, March 26, 2017

mongoDB Backup and Restore



Install MongoDB Community Edition on Ubuntu (Optional)

  1. Import the public key used by the package management system.
    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
  2. Create a list file for MongoDB.
    (Trusty) echo "deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
    (Xenial) echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
  3. Reload local package database
    sudo apt-get update
  4. Install the MongoDB packages (Client only)
    sudo apt-get install -y mongodb-org-shell mongodb-org-tools


Backup (Source database from INET Cloud)

mongodump --host=172.17.0.3 --port=27017 \
--username=nutt --password=P@ssw0rd1 \
--authenticationDatabase=admin \
--db=settrade \
--archive=/home/ubuntu/backup/settrade.dmp \
--gzip \
--dumpDbUsersAndRoles \
--verbose=5


Restore (Database on Windows as destination)

mongorestore /host:127.0.0.1 /port:27017 /db:settrade /gzip /drop /restoreDbUsersAndRoles /archive:settrade.dmp
When run montorestore command on Ubuntu, an arguments changes as below:
mongorestore --host=172.17.0.1 --port=27017 --db=settrade --gzip --drop --restoreDbUsersAndRoles --archive=settrade.dmp

Check number of objects in databases (ensure data structure correctly should run db.collection.validate({full: true}) before counting)

use settrade
var collections = db.getCollectionNames();
print('Collections inside the db:');
for(var i = 0,c = 0; i < collections.length; i++){
  var name = collections[i];
  if(name.substr(0, 6) != 'system')
    print(name + ' - ' + db[name].count() + ' records');
    c = c + db[name].count()
}
print("All objects in db: ",c)