connecting a mongodb created in mongolab through a java application
Asked Answered
T

1

10

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?

Thirzia answered 24/2, 2013 at 13:13 Comment(0)
W
21

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);
Waistcoat answered 24/2, 2013 at 15:31 Comment(2)
Is there any possibilitiesto set two host with username and password in MongoURIRevoke
You should be able to add the list of host/ports as a comma separated list: mongodb://admin:[email protected]:41177,ds041178.mongolab.com:41177/myclouddb. I am not sure that all drivers support this format but it is in the spec: docs.mongodb.org/manual/reference/connection-stringWaistcoat

© 2022 - 2024 — McMap. All rights reserved.