Skip to content

Instantly share code, notes, and snippets.

@dwbutler
Forked from ches/db.rake
Created August 28, 2013 22:56
Show Gist options
  • Save dwbutler/6372435 to your computer and use it in GitHub Desktop.
Save dwbutler/6372435 to your computer and use it in GitHub Desktop.
namespace :db do
desc 'Open a MongoDB console with connection parameters for the current Rails.env'
task :console, [:session] => :environment do |t, args|
session_name = args[:session] || :default
config = Mongoid.sessions[session_name]
username = config[:username]
password = config[:password]
database = config[:database]
session = Mongoid::Sessions.with_name(session_name)
host = session.cluster.with_primary {|node| node.resolved_address}
args = []
args << "--username=#{username}" if username
args << "--password=#{password}" if password
args << "--host=#{host}"
args << database
exec 'mongo', *args
end
end
@dwbutler
Copy link
Author

Brought up-to-date to support replica sets and Mongoid sessions. It will always connect to the primary automatically.

Usage:

rake db:console[session]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment