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

3.3k Views Asked by At

I have a multi-domain Rails 4 app where the request.domain of the http request determines which functionality I expose a given visitor to.

Each domain in my app should be served by its own MongoDB database. E.g. domain1.com is served by db_for_domain_1, etc.

I can read in the MongoDB docs on runtime persistence that

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

enables me to switch database on the fly.

But how do I keep the persistence when I bypass Mongoid and use the mongo Shell method db.collection.insert()? I will still do it from within my application though.

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

MyModel.collection.insert({field_1: "Value 1", field_2: "Value 2"})
1

There are 1 best solutions below

3
Steve Tarver On

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

mongo db_for_domain_1:<port>/<dbName>

and then

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

see mongo --help for username and password options.