Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"})
like image 313
Cjoerg Avatar asked Oct 14 '15 11:10

Cjoerg


People also ask

Which of the following command is used to insert data into collection MongoDB?

To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.

How do I select a database in MongoDB?

Open a new database connection. Open a connection to a new server using new Mongo() . Use getDB() method of the connection to select a database.


1 Answers

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.

like image 63
Steve Tarver Avatar answered Oct 22 '22 14:10

Steve Tarver