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?
To connect to a MongoDB Server using username and password, you have to use 'username@hostname/dbname'. Where username is the username, password is the password for that user and dbname is the database to which you want to connect to. Note : You can use multiple hostname to connect to with a single command.
To connect to your local MongoDB, you set Hostname to localhost and Port to 27017 . These values are the default for all local MongoDB connections (unless you changed them). Press connect, and you should see the databases in your local MongoDB.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With