Sheharyar Naseer

MongoSync Ruby Gem

In my previous post, I had written about my mongo-sync shell script that allows you to sync Local and Remote Mongo Databases. I spent the last day converting it into a Ruby Gem so that you can perform actions using nice Rake Tasks and invoke the commands from Rails Console or irb.

MongoSync Ruby Gem Demo GIF

If the gif above wasn’t explanatory enough, start by adding it to your Gemfile:

gem 'mongo_sync', group: :development

Bundle and run the generator to create configuration template:

$ bundle
$ rails g mongo_sync:config

Edit the newly created config/mongo_sync.yml, putting in details of your remote and local DBs:

  db: 'local_db_name'

  db: 'remote_db_name'
    url: ''
    port: 27017
    username: 'remote_mongo_user'
    password: 'remote_mongo_pass'

# For Heroku MongoDB URLs, here's the legend:
# mongodb://

# All fields are required

To Sync, use these rake tasks:

rake mongo_sync:push       # Push DB to Remote
rake mongo_sync:pull       # Pull DB to Local

You can use it in rails console as well:

require 'mongo_sync'


# You can also pass path to a custom config file
MongoSync.push "path/to/custom/mongo_sync.yml"

A few important things to note are:

  • mongodb needs to be installed on your system (obviously)
  • Pushing/Pulling overwrites the Target DB
  • It’s a good idea to keep your mongo_sync.yml in .gitignore or load the values from the ENV

There’s still much to do but for now it should work perfectly with your Rails Projects.