Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB java connection issues [duplicate]

Tags:

java

mongodb

I am trying to run the following code:

public static void main(String args[]) throws UnknownHostException, MongoException{
        Mongo m = new Mongo( "localhost", 27017 );
        DB db = m.getDB( "test" );


        Set<String> coll = db.getCollectionNames();
    }

but for some reason I am getting connection issues :

bc:java.net.ConnectException: Connection refused: connect

EDIT: Nvm I forgot to run the database in the background

like image 336
fogy Avatar asked May 09 '11 15:05

fogy


1 Answers

Obviously, make sure you can connect to MongoDB on "localhost" port 27017. You should be able to open the MongoDB shell with no arguments and get a prompt back:

» mongo
MongoDB shell version: 1.8.1
connecting to: test
> 

If you can't the answer should be obvious: MongoDB isn't running. You'll want to make sure you start up the MongoDB server process. There are some Quickstart Guides in the MongoDB Docs which should guide you to the process on your platform of choice.

Otherwise, you don't indicate what platform you are on but there is an issue with how Java resolves certain hostnames like "localhost" on Mac OS X... This is actually a Java issue rather than a MongoDB Java Driver issue.

When asked to resolve "localhost" from a hostname to an InetSocketAddr, Java for Mac will typically return the IP for your machine's external interface. As a few installers for Mac MongoDB like Homebrew lock the listening IP Address to 127.0.0.1, this can cause connecting to "localhost" to fail completely on Mac with Java.

like image 99
Brendan W. McAdams Avatar answered Sep 26 '22 01:09

Brendan W. McAdams