connecting a mongodb created in mongolab through a

2019-03-18 17:46发布

问题:

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?

回答1:

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);