How to programmatically get the current database Mongoid is writing to?
Asked Answered
P

5

14

I am talking to multiple databases using Mongoid.override_database("database_name") using Mongoid with rails. How do I find the current database programmatically?

Mongoid docs on sessions: http://mongoid.org/en/moped/docs/driver.html define methods to override database but do not define a way to get the current database in use.

Polytrophic answered 23/10, 2012 at 21:15 Comment(0)
P
26

Got it!

Mongoid.default_session.options[:database]
Polytrophic answered 23/10, 2012 at 21:30 Comment(4)
It's now by symbol: Mongoid.default_session.options[:database]Trembly
Warning, this is NOT thread safe!! - if you are switching databases in a before_filter in your application controller, this returns the database name used in other threads in the application.Illaffected
This seems to be deprecated.Fiume
It is now Mongoid.default_client.options[:database]Hautboy
M
8

The new way to get this is

Mongoid::Config.clients["default"]["database"]

You can also just have a look at

Mongoid::Config.clients

to see what else is available.

Mide answered 22/9, 2016 at 0:38 Comment(1)
You can use symbols as well. Mongoid::Config.clients[:default][:database]Annunciation
U
4

If you want the overrided database you actually need to use

Mongoid::Threaded.database_override
Unorthodox answered 25/12, 2012 at 14:13 Comment(0)
B
4

Mongoid Version 7.0.5

Mongoid.client(:default).database
Brundisium answered 6/8, 2020 at 14:38 Comment(0)
D
2

Running Mongoid.default_session.options[:database] gives an error that default_session is invalid. It is now default_client. That works wonderfully.

Run it without the [:database] to get all the option and see the full configuration of your database.

Mongoid::Config.clients["default"]["database"] assumes you are NOT using the uri version of mongoid.yml. You will get nil in all cases. Use Mongoid::Config.clients["default"] to get the full configuration of the current database, or Mongoid::Config.clients["default"]['uri'] to give you just the full uri.

Pick the database name from the URI after the last port number/. There could be severalif using a sharded configuration

Doublebreasted answered 22/8, 2017 at 7:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.