Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connecting a mongodb created in mongolab through a java application

Tags:

java

mongodb

mlab

i created a mongodb instance in mongolab It provided me with a connection URI.

   mongodb://<dbuser>:<dbpassword>@ds041177.mongolab.com:41177/myclouddb

I used the following java code to connect to my database-

      Mongo m = new Mongo();
     com.mongodb.DBAddress dba=new DBAddress("mongodb://admin:[email protected]:41177/myclouddb");
        m.connect(dba);

But this throws a NumberFormatException

   java.lang.NumberFormatException: For input string: ""

What am i doing wrong?

like image 785
user1946152 Avatar asked Feb 24 '13 13:02

user1946152


People also ask

How do I connect to a MongoDB connection?

To connect to a MongoDB Server using username and password, you have to use 'username@hostname/dbname'. Where username is the username, password is the password for that user and dbname is the database to which you want to connect to. Note : You can use multiple hostname to connect to with a single command.

How do I link my local application to MongoDB?

To connect to your local MongoDB, you set Hostname to localhost and Port to 27017 . These values are the default for all local MongoDB connections (unless you changed them). Press connect, and you should see the databases in your local MongoDB.


1 Answers

That is a MongoDB URI.

Instead of passing it to a DBAddress just pass it to a MongoURI and then pass that to the Mongo instance.

String textUri = "mongodb://admin:[email protected]:41177/myclouddb";
MongoURI uri = new MongoURI(textUri);
Mongo m = new Mongo(uri);

You should also consider upgrading to the latest driver and switching to the MongoClient class as the Mongo class is now deprecated.

String textUri = "mongodb://admin:[email protected]:41177/myclouddb";
MongoClientURI uri = new MongoClientURI(textUri);
MongoClient m = new MongoClient(uri);
like image 60
Rob Moore Avatar answered Oct 23 '22 21:10

Rob Moore