Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default database for MongoDB shell

When I go into the mongo shell in my terminal, it always starts with the database test, which is the wrong database. Can you set mongo to start in a specific database?

like image 339
Holger Sindbaek Avatar asked Jul 04 '12 23:07

Holger Sindbaek


People also ask

How do I change the default database in MongoDB?

Find .Use ls -a in Terminal to see all hidden files. This file automatically runs when a user logs into the mongo shell and you can set your default database at that time.

What is the default database path for MongoDB?

The default dbpath for mongodb is /data/db .

How do I start MongoDB in shell?

To open up the MongoDB shell, run the mongo command from your server prompt. By default, the mongo command opens a shell connected to a locally-installed MongoDB instance running on port 27017 . Try running the mongo command with no additional parameters: mongo.

How do I start MongoDB from terminal?

To start MongoDB, run mongod.exe from the Command Prompt navigate to your MongoDB Bin folder and run mongod command, it will start MongoDB main process and The waiting for connections message in the console.


2 Answers

Command Line

You can select the database to use on the mongo command line, eg for 'mydb':

mongo mydb 

If a database name is not provided, 'test' will be used.

In .mongorc.js

If you want to set a default database without specifying on the command line each time, you can add a line to the .mongorc.js file in your home directory:

db = db.getSiblingDB("mydb") 

The .mongorc.js file is executed after the mongo shell is started, so if you set a default here it will override a database specified on the command line.

like image 74
Stennie Avatar answered Oct 15 '22 03:10

Stennie


It's entirely possible to set a default, albiet in a slightly strange way. Here's what I do for using automatic authentication to an admin in .mongorc.js:

// Persist the database selected var selectedDB = db  // Authenticate db = db.getSiblingDB("admin") db.auth('admin','adminpass')  // Switch back to selected DB db = selectedDB  // Universally allow read queries on secondaries from shell.  rs.slaveOk() 

To directly answer the question, I'd think the way to accomplish this is simply by executing a check to see if the current database loaded up is "test" and alter only if that's the case, so.

if (db.name == 'test')   db.getSiblingDB('yourdefaultdb') 

This allows both selecting a database at the command line and setting a default. Naturally it'll prevent you from overriding and using the "test" db from the command line, but I think that's a bit of a strange use case given the question. Cheers.

like image 41
bradq Avatar answered Oct 15 '22 05:10

bradq