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:password@ds041177.mongolab.com:41177/myclouddb");
        m.connect(dba);

But this throws a NumberFormatException

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

What am i doing wrong?

user1946152
  • 375
  • 1
  • 9
  • 24

1 Answers1

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:password@ds041177.mongolab.com: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:password@ds041177.mongolab.com:41177/myclouddb";
MongoClientURI uri = new MongoClientURI(textUri);
MongoClient m = new MongoClient(uri);
chrisjleu
  • 4,329
  • 7
  • 42
  • 55
Rob Moore
  • 3,343
  • 17
  • 18
  • Is there any possibilitiesto set two host with username and password in MongoURI – Ganesa Vijayakumar Jan 13 '15 at 12:23
  • You should be able to add the list of host/ports as a comma separated list: mongodb://admin:password@ds041177.mongolab.com:41177,ds041178.mongolab.com:41177/myclouddb. I am not sure that all drivers support this format but it is in the spec: http://docs.mongodb.org/manual/reference/connection-string/ – Rob Moore Jan 15 '15 at 01:55