How to switch MongoDB database on the fly when using db.collection.insert ()?

I have a multi-domain Rails 4 application where request.domain http request determines what functionality I expose to this visitor.

Each domain in my application must serve its own MongoDB database. For instance. domain1.com is served by db_for_domain_1 etc.

I can read in MongoDB docs about runtime which

 Mongoid.override_database("db_for_#{request.domain}") 

allows me to switch the database on the fly.

But how to maintain safety when I overtake Mongoid and use the mongo Shell method db.collection.insert () ? I will still do this from my application.

The answer may be in the MongoDB collection access docs , but I don't get it. So, how do I switch the database before / during this operation ?:

 MyModel.collection.insert({field_1: "Value 1", field_2: "Value 2"}) 
+6
source share
1 answer

If I understand your question correctly: do you have an application that connects to various mongodbs on different servers, but you want to use the mongo shell to connect to the database outside of your application? If true, you must connect to the desired database through the shell using

 mongo db_for_domain_1:<port>/<dbName> 

and then

 db.<collectionName>.insert({doc}) 

see mongo --help for username and password options.

+4
source

All Articles