MongoDB connection string causing issue

Hi, I am working with MongoDB and want to integrate it with my application. I am using Mongo SDK to do so.
I went through this: https://www.mongodb.com/docs/manual/reference/connection-string/#srv-connection-format and want to leverage both connection string formats.
I am using same credentials and able to connect using mongodb+srv://[username:password@]host[/[defaultauthdb][?options]]
but facing error while using this format:
mongodb+srv://[username:password@]host[/[defaultauthdb][?options]]

Below is the error I am facing

Error opening connection. Exception is Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{[address=cluster0-zvxcp.mongodb.net:27017](http://address=cluster0-zvxcp.mongodb.net:27017/), type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: [cluster0-zvxcp.mongodb.net](http://cluster0-zvxcp.mongodb.net/)}, caused by {java.net.UnknownHostException: [cluster0-zvxcp.mongodb.net](http://cluster0-zvxcp.mongodb.net/)}}]

Could anyone let me know what is the issue and guide me?

Can you post your code?
Of course, do not reveal your actual username or password.

public static void main(String args) throws ConnectionException {
DatabaseParameters dbparam = new DatabaseParameters();
dbparam.setConnectionUrl(“mongodb:[username:password@]host[/[defaultauthdb]/?authMechanism=SCRAM-SHA-1”);
ConnectionString connString = new ConnectionString(dbparam.getConnectionUrl());
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(connString)
.retryReads(false)
.retryWrites(false)
.applyToSslSettings(builder →
builder.enabled(true))
.build();
client = MongoClients.create(settings);
MongoDatabase db = client.getDatabase(“testdb”);
MongoIterable collections = db.listCollectionNames();
MongoCursor cursorCollection = collections.iterator();
if (!cursorCollection.hasNext()) {
String msg = “No Database Found”;
throw new ConnectionException(msg, msg, null);
}
}
Please look into the above code while using the format : mongodb://[username:password@]host1[:port1][,…hostN[:portN]][/[defaultauthdb][?options]]
I am getting the error .
And while using the below format the connection is successful
mongodb+srv://[username:password@]host[/[defaultauthdb][?options]]

2 problems with the code you posted:

  1. You should format it with the ` ` ` three ticks ` ` ` syntax so it’s readable … even helpful people will not bother to read unformatted code!
  2. You did not include the import statements so it can’t be compiled.
1 Like

You should probably post a body of code that can be compiled and run with main that takes the URI as an argument. That will show the error and make it easy to provide help. And in preparing such an example, you might happen to find the problem!

Hi below is formatted code which is throwing error.

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;

public class ConnPoc {

  private static MongoClient client;

  public static void main(String[] args) {
    ConnectionString connString = new
        ConnectionString("mongodb://{username}:{pass}@{host}/?authMechanism=SCRAM-SHA-1"
);
    MongoClientSettings settings = MongoClientSettings.builder()
        .applyConnectionString(connString)
        .retryReads(false)
        .retryWrites(false)
        .applyToSslSettings(builder -> builder.enabled(true))
        .build();

    client = createMongoClient(settings);
    MongoDatabase db = client.getDatabase("databaseName");
    MongoIterable<String> collections = db.listCollectionNames();
    MongoCursor<String> cursorCollection = collections.iterator();
    if (!cursorCollection.hasNext()) {
      throw new RuntimeException("No Database Found");
    }
  }

  public static MongoClient createMongoClient(MongoClientSettings settings) {
    return MongoClients.create(settings);
  }
}

Below is the stack trace

Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address={myHost}:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: {myHost}}, caused by {java.net.UnknownHostException: {myHost}}}]
	at com.mongodb.internal.connection.BaseCluster.getDescription(BaseCluster.java:177)
	at com.mongodb.internal.connection.SingleServerCluster.getDescription(SingleServerCluster.java:42)
	at com.mongodb.client.internal.MongoClientDelegate.getConnectedClusterDescription(MongoClientDelegate.java:135)
	at com.mongodb.client.internal.MongoClientDelegate.createClientSession(MongoClientDelegate.java:95)
	at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.getClientSession(MongoClientDelegate.java:266)
	at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:170)
	at com.mongodb.client.internal.MongoIterableImpl.execute(MongoIterableImpl.java:135)
	at com.mongodb.client.internal.MongoIterableImpl.iterator(MongoIterableImpl.java:92)
	at com.mongodb.client.internal.MappingIterable.iterator(MappingIterable.java:39)
	at org.jitterbit.connector.mongodb.ConnPoc.main(ConnPoc.java:41)
1 Like

The fact that you have {myHost} verbatim in the error message, rather that have a real host name such as localhost,

makes me think that you are missing some configuration. Things like the curly braces indicate place holders that you have to fill with real values.

However, your OP shows otherwise:

But the above address is a cluster and would usually caused another type of DNS error because the address is not an host.

Your code

specifies the use of an host. If you connect to a cluster like your OP hints at, you must use mongodb+srv:// rather than mongodb://.

The differences between the 2 are explained in the link you shared in the OP.

1 Like

Hi, @steevej For {myHost} I put it by myself in the logs to hide the actual host. I am already using an actual value.

But the above address is a cluster and would usually cause another type of DNS error because the address is not a host.

Okay, so I guess we need to connect with SQL Atlas and then we can get the generated host and use it.
I did connect to SQL Atlas and used the generated host, it is working fine for me.
Thanks

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.