Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to a specific database by default in mongodb

I am running a mongodb on a linux box. So every time I connect to it from the console (typing mongo) I get something like this:

MongoDB shell version: 2.4.9
connecting to: test

And then I am doing use myDatabase (where myDatabase is 99% is the same). So basically I always do some unneeded type of work. Is there a way to configure mongo, so that it will connect to myDatabase by default?

like image 950
Salvador Dali Avatar asked Mar 15 '14 00:03

Salvador Dali


People also ask

What is the default database path for MongoDB?

The default dbpath for mongodb is /data/db .


2 Answers

Surprised that I don't find a duplicate of this. Okay, now we have content.

From the command line, just do this:

$ mongo myDatabase

This actually is covered in the documentation, albeit down the page somewhat. No direct link but search for <db address> and the same example is there.

Of course you could have done:

$ mongo --help
MongoDB shell version: 2.4.9
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
    foo                   foo database on local machine
    192.169.0.5/foo       foo database on 192.168.0.5 machine
    192.169.0.5:9999/foo  foo database on 192.168.0.5 machine on port 9999

Which shows the usage along with other options you can pass in.

Another thing, not quite a default connect but a shortcut is you can do this in the .mongorc.js file:

db=db.getSiblingDB("myDatabase")

Which assigns the variable db to that database so now:

db.collection.find()

Is acting on myDatabase.

like image 176
Neil Lunn Avatar answered Oct 21 '22 09:10

Neil Lunn


As per latest mongodb drivers, we can provide default database name in connection string like this:

1. Connect using the mongoShell

mongo "mongodb+srv://sandbox.ununu.mongodb.net/mydatabase" --username user001

2. Connect using the drivers

mongodb+srv://user001:<password>@sandbox.ununu.mongodb.net/mydatabase?retryWrites=true&w=majority

Details of parametere:

  • Replace mydatabase with the name of the database that connections will use by default.
  • sandbox.ununu.mongodb.net is your cluster name
  • You will be prompted for the password for the Database User,user001.
  • user001 is username

For more details on passing ReplicaSet, other query string parameters, etc. refer mongodb official document. document link

like image 1
KushalSeth Avatar answered Oct 21 '22 09:10

KushalSeth