Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically get the current database Mongoid is writing to?

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.

like image 779
Vamshidhar Behara Avatar asked Oct 23 '12 21:10

Vamshidhar Behara


People also ask

How do I get current database in MongoDB?

getName() Returns: the current database name.

What is the command to check the current DB in use?

mysql> show databases; Here is the output that displays all the databases. As you can see above, we have both databases, and we can get the current database name with the help of DATABASE() method.

How can check current user in MongoDB?

To list existing users in MongoDB, you can use the db. getUsers() method to show all of the users within the current database.

How do I list a database in MongoDB?

There are different mongo shell list Databases commands in MongoDB. These commands can be run on the Mongo Shell to return the list of databases running on your MongoDB server. The show dbs Mongo Shell command returns the list of all databases running on MongoDB Server including default and user-defined databases.


4 Answers

Got it!

Mongoid.default_session.options[:database]
like image 176
Vamshidhar Behara Avatar answered Oct 18 '22 20:10

Vamshidhar Behara


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.

like image 29
user1130176 Avatar answered Oct 18 '22 22:10

user1130176


If you want the overrided database you actually need to use

Mongoid::Threaded.database_override
like image 21
Nightscape Avatar answered Oct 18 '22 22:10

Nightscape


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

like image 38
Donald French Avatar answered Oct 18 '22 21:10

Donald French