Connect to a specific database by default in mongodb

大憨熊 提交于 2019-12-01 07:35:24

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!