connecting a mongodb created in mongolab through a java application

自作多情 提交于 2019-12-03 17:19:59

问题


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


来源:https://stackoverflow.com/questions/15052074/connecting-a-mongodb-created-in-mongolab-through-a-java-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!