Java with MongoDb IP connecting issue - java

I write a Java program to connect MongoDb and write some data into it. For example I set up the MongoDb on 192.168.1.95 and run my program on that server. When I use the following code:
MongoClient mongo = new MongoClient("localhost", 27017);
It is working and no any problem. However, if I use
MongoClient mongo = new MongoClient("192.168.1.95", 27017);
It always throw a exception for me:
Exception in thread "main" com.mongodb.MongoException: unauthorized
at com.mongodb.CommandResult.getException(CommandResult.java:100)
at com.mongodb.CommandResult.throwOnError(CommandResult.java:134)
at com.mongodb.DBTCPConnector._checkWriteError(DBTCPConnector.java:142)
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:183)
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:155)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:270)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
at com.mongodb.DBCollection.insert(DBCollection.java:75)
at com.mongodb.DBCollection.insert(DBCollection.java:59)
at com.mongodb.DBCollection.insert(DBCollection.java:104)
at com.starscriber.mongoCluster.Main.main(Main.java:29)
Why cannot I use the exactly Ip instead of "localhost"?? And I am pretty sure that I don't need any username and password to log into the MongoDb

Sounds like auth=true in your MongoDB server configuration. If so, you need to log in to your server by connecting over the localhost interface for the first time to create user credentials. For more info see section "Security Considerations" in the Run-time Database Configuration page of the MongoDB manual

Related

com.mongodb.MongoSocketException: No such host is known

I am trying to connect to MongoDB Atlas DB from my spring boot app. I set the below listed properties in my application properties file. When I try to connect I see this exception "com.mongodb.MongoSocketException: No such host is known". However I am able to connect to this using mongodb compass from the same machine. Am I missing something?
spring.data.mongodb.authentication-database=
spring.data.mongodb.host=
spring.data.mongodb.port=
spring.data.mongodb.username=
spring.data.mongodb.password=
spring.data.mongodb.database=
I am also able to connect when I use the below -
spring.data.mongodb.uri=
Take a look at this: https://developer.mongodb.com/article/srv-connection-strings/
Atlas is giving you a connection string with the mongodb+srv syntax where the "host" part is actually a DNS SRV record that gives you a replica set, not a host. This is compatible with the spring.data.mongodb.uri parameter and of course with MongoDb compass.
However setting the spring.data.mongodb.host instead gives you the unknown host exception.

Have Java's Mongo Driver throw an exception if it can't connect to server

Is there a way of having Java's Mongo client (version 2.13.2) throw an exception if it couldn't connect to the server?
I have a line in my code like the one shown below:
mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
and I like it to throw an exception if the server is down and the connection failed.
I've seen other answers in Stack Overflow and the Mongo mailing list, but all of them seem to go through attempting to fetch a database using the MongoClient and see if it throws and Exception. I would very much would like to avoid that if possible. I don't want to get a database: I want to test connectivity (they're different things, and testing by trying to get a database seems... dirty)
If I try to set a read preference (mongoClient.setReadPreference(ReadPreference.secondaryPreferred());) I do see an exception in the console:
INFO [2016-01-29 16:56:43,847] org.mongodb.driver.cluster: Exception in
monitor thread while connecting to server localhost:27017
! java.net.ConnectException: Connection refused
but that is not even bubbled up.. it seems to be failing in another process or thread or being caught?
Thank you in advance

How can I connect to MongoDB server using JAVA from OpenShift?

I have created a MongoDB instance in OpenShift. I can connect to it via RockMongo, which is a service offered by OpenShift.
I'm trying to connect to my instance using JAVA, but I just receive a Connection refuesed error. Moreover, I cannot connect it using RoboMongo.
In my RockMongo status tab, I see the following information:
Host: 127.11.201.2
Port: 27017
Using RoboMongo with MongoLab instance works just fine giving it the right credentials, but here with OpenShift it fails on connecting to the instance.
In my JAVA app I'm trying the following:
MongoCredential credential = MongoCredential.createCredential(
Const.MONGO_USERNAME, Cont.MONGO_DB,
Const.MONGO_PASSWORD.toCharArray());
mongo = new MongoClient(new ServerAddress(Const.MONGO_URI), Arrays.asList(credential));
With 127.11.201.2 as MONGO_URI.
Why am I failing to connect to my instance? What am I doing wrong?
P.S using putty I am able to connect to my mongo instance by just executing the command mongo.
OpenShift provides environment variables, which you should use to connect to your MongoDB.
OPENSHIFT_MONGODB_DB_HOST The MongoDB IP address
OPENSHIFT_MONGODB_DB_PORT The MongoDB port
OPENSHIFT_MONGODB_DB_USERNAME The MongoDB username
OPENSHIFT_MONGODB_DB_PASSWORD The MongoDB password
OPENSHIFT_MONGODB_DB_URL The MongoDB connection URL (e.g. mongodb://<username>:<password>#<hostname>:<port>/)
I'm using one line of code to connect to the database:
new MongoClient(new MongoClientURI(System.getenv("OPENSHIFT_MONGODB_DB_URL")));

How to add OpenShift MongoDB environment variables to my Java Application [duplicate]

I have created a MongoDB instance in OpenShift. I can connect to it via RockMongo, which is a service offered by OpenShift.
I'm trying to connect to my instance using JAVA, but I just receive a Connection refuesed error. Moreover, I cannot connect it using RoboMongo.
In my RockMongo status tab, I see the following information:
Host: 127.11.201.2
Port: 27017
Using RoboMongo with MongoLab instance works just fine giving it the right credentials, but here with OpenShift it fails on connecting to the instance.
In my JAVA app I'm trying the following:
MongoCredential credential = MongoCredential.createCredential(
Const.MONGO_USERNAME, Cont.MONGO_DB,
Const.MONGO_PASSWORD.toCharArray());
mongo = new MongoClient(new ServerAddress(Const.MONGO_URI), Arrays.asList(credential));
With 127.11.201.2 as MONGO_URI.
Why am I failing to connect to my instance? What am I doing wrong?
P.S using putty I am able to connect to my mongo instance by just executing the command mongo.
OpenShift provides environment variables, which you should use to connect to your MongoDB.
OPENSHIFT_MONGODB_DB_HOST The MongoDB IP address
OPENSHIFT_MONGODB_DB_PORT The MongoDB port
OPENSHIFT_MONGODB_DB_USERNAME The MongoDB username
OPENSHIFT_MONGODB_DB_PASSWORD The MongoDB password
OPENSHIFT_MONGODB_DB_URL The MongoDB connection URL (e.g. mongodb://<username>:<password>#<hostname>:<port>/)
I'm using one line of code to connect to the database:
new MongoClient(new MongoClientURI(System.getenv("OPENSHIFT_MONGODB_DB_URL")));

mongo couldn't connect to [localhost/127.0.0.1:27017]

I'm getting the following error:
נוב 08, 2013 12:05:46 PM com.mongodb.DBTCPConnector initDirectConnection
WARNING: Exception executing isMaster command on localhost/127.0.0.1:27017
java.io.IOException: couldn't connect to [localhost/127.0.0.1:27017] bc:java.net.ConnectException: Connection refused: connect
at com.mongodb.DBPort._open(DBPort.java:214)
at com.mongodb.DBPort.go(DBPort.java:107)
at com.mongodb.DBPort.go(DBPort.java:88)
at com.mongodb.DBPort.findOne(DBPort.java:143)
at com.mongodb.DBPort.runCommand(DBPort.java:148)
at com.mongodb.DBTCPConnector.initDirectConnection(DBTCPConnector.java:548)
at com.mongodb.DBTCPConnector.checkMaster(DBTCPConnector.java:527)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:277)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:257)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:310)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:295)
at com.mongodb.DB.getCollectionNames(DB.java:412)
at Main.Main.main(Main.java:26)
my code is simple (my first time with mongo):
MongoClient Client = new MongoClient( "localhost" , 27017 );
DB db = Client.getDB("qw");
DBCollection coll[] = new DBCollection[4];
Set<String> colls = db.getCollectionNames();
for(String s: colls)
System.out.println(s);
what is the problem?
Possibly you haven't started the Mongo server.
Open a shell and type
mongod
On the file system, you can start it from $MONGO_INSTALL_PATH/bin/mongod.
Don't close the shell and then try to run your code again.
More info:
Manage the mongod process
Try restarting your mongo. I had the same problem, and restarting solved it for me.
You haven't started your MongoDB Server.
First start your mongodb server and then run your code.
Or
You can also create MongoDB service which will always be running in the background, so from next time onwards you don't have to start the MongoDB server.
Here are the steps to create MongoDB service:
Create a folder named ‘log’ parallel to ‘data’ folder, inside mongodb folder.
Copy the ‘mongo.config’ file parallel to log folder inside ‘mongodb’ folder.
Here is the content for your mongo.config file:
stores data here
dbpath = your_drive\mongodb-win32-x86_64-2.2.3\data\db
all output goes here
logpath = your_drive\mongodb-win32-x86_64-2.2.3\log\mongo.log
log read and write operations
diaglog = 3
Create a file MongoServer.bat,
Here is the content for MongoServer.bat
your_drive\mongodb-win32-x86_64-2.2.3\bin\mongod.exe --config "your_drive\mongodb-win32-x86_64-2.2.3\mongo.config"
On your command prompt, go to your mongodb\bin directory and then write this command,
mongod --config your_Drive\mongodb-win32-x86_64-2.2.3\mongo.config –install
This will create the service named as ‘Mongo DB’.
To start the service, type on command prompt
net start MongoDB.
Hence, your service is created. Now you can perform your task.
For further information, you can visit website.
Probably not your problem, but I've seen this Exception raised when mongodb is refusing the connection because it hit a limit on the number of open connections. Check your mongodb log file for a statement like:
"connection refused because too many open connections".
This can mean you're leaving connections open, or you need to raise the limit on number of open files in the db server.
Seems to have the same problem when using the below code to the connection
MongoClient mongo = new MongoClient("localhost", 27017);
But worked out when changed to
MongoClient mongo = new MongoClient("127.0.0.1", 27017);

Categories

Resources