Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

mongo shell - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...