Connect mongodb created in mongolab through Java application

I created a mongodb instance in Mongolian

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

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

However, this raises numberformatexception

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

What on earth did I do wrong?

Solution

That is a mongodb URI

Instead of passing it to dbaddress, just pass it to mongouri and then to 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, because 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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>