8

Trying to connect Atlas cluster via Java driver using MongoDB version 3.6.

So, I'm writting like:

 MongoClientURI uri = new MongoClientURI("mongodb+srv://admin:mypassword@cluster0-ox90k.mongodb.net/test?retryWrites=true");
 MongoClient mongoClient = new MongoClient(uri);

In this case the error is:

java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with 'mongodb://'
    at com.mongodb.ConnectionString.<init>(ConnectionString.java:203)
    at com.mongodb.MongoClientURI.<init>(MongoClientURI.java:176)
    at com.mongodb.MongoClientURI.<init>(MongoClientURI.java:158)
    at project.Bot.check(Bot.java:30)
    at project.Bot.onUpdateReceived(Bot.java:104)
    at java.util.ArrayList.forEach(ArrayList.java:1249)
    at org.telegram.telegrambots.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
    at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:309)

When the program starts with snippet using MongoDB version 3.6 or later without +srv:

MongoClientURI uri = new MongoClientURI("mongodb://admin1:mypassword@cluster0-ox90k.mongodb.net/test?retryWrites=true");
MongoClient mongoClient = new MongoClient(uri);

I'm getting an error: enter image description here

com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=cluster0.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: cluster0.mongodb.net}, caused by {java.net.UnknownHostException: cluster0.mongodb.net}}]
    at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:369)
    at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)
    at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
    at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
    at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63)
    at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:201)
    at com.mongodb.operation.CountOperation.execute(CountOperation.java:206)
    at com.mongodb.operation.CountOperation.execute(CountOperation.java:53)
    at com.mongodb.Mongo.execute(Mongo.java:772)
    at com.mongodb.Mongo$2.execute(Mongo.java:759)
    at com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:185)
    at com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:170)
    at project.Bot.check(Bot.java:36)
    at project.Bot.onUpdateReceived(Bot.java:103)
    at java.util.ArrayList.forEach(ArrayList.java:1249)
    at org.telegram.telegrambots.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
    at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:309)

In POM file I have dependency:

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.6.0</version>
        </dependency>

Also, when I'm starting mongo my database is added to this address mongodb://127.0.0.1:27017, but I added path to the cluster not for this. Maybe I need to write path to concrete cluster or?

Ofc, I have admin-user. In addition, I can connect via Compass to my cluster and from shell. mongod process is started. This error appears only, when I'm running in IDE. Same issue probably here.

Does anyone know how to solve this error? I appreciate any help.

invzbl3
  • 5,872
  • 9
  • 36
  • 76
  • Will it help if you change "cluster0.mongodb.net" with exact ip address? – y.bedrov Jun 19 '18 at 09:33
  • @y.bedrov, if I write a local address, for instance? Yes, I can connect to local address, but I don't know, why IDE tell me about the error, maybe it's wrong command or need to add something. This error appears even if I try to connect to local address. – invzbl3 Jun 19 '18 at 23:49

7 Answers7

6

Solved it! So, what I've done:

  1. I tried only to connect to tier cluster via driver3.6 and wrote

    mongodb+srv://user:@cluster0-ox90k.mongodb.net/test?retryWrites=true

I always get an error: Connection strings must start with 'mongodb://'.

  1. Okay, I deleted the snippet +srv and wrote the same way

    mongodb://user:@cluster0-ox90k.mongodb.net/test?retryWrites=true

and get again the error:

com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=cluster0-ox90k.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: cluster0-ox90k.mongodb.net}, caused by {java.net.UnknownHostException: cluster0-ox90k.mongodb.net}}]

So, I wrote via driver3.4 or earlier like

mongodb://user:<PASSWORD>@cluster0-shard-00-00-ox90k.mongodb.net:27017,cluster0-shard-00-01-ox90k.mongodb.net:27017,cluster0-shard-00-02-ox90k.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true

and finally it solved.

Note: You can get this connection string from the Atlas management console by setting your Java driver to '3.4 or later'. This will help you avoid having to come up with the connection string yourself.


Updated: if you want to use drivers 3.7+, you need to write instead of format connection (and to avoid my issues above)

MongoClientURI uri = new MongoClientURI("mongodb+srv://admin:mypassword@cluster0-ox90k.mongodb.net/test?retryWrites=true");
MongoClient mongoClient = new MongoClient(uri);

another variant using MongoClients.create() (as of the 3.7 release), and as mentioned here:

   MongoClient mongoClient = MongoClients.create("mongodb+srv://admin:mypassword@cluster0-ox90k.mongodb.net/test?retryWrites=true");

Note: the password need to write not like mongodb://user:<mypassword>@...,

just in format mongodb://user:mypassword@...

without braces <>.

checklist
  • 12,340
  • 15
  • 58
  • 102
invzbl3
  • 5,872
  • 9
  • 36
  • 76
2

There seem to be a few issues here

First

3.6.0 is not the Mongo driver library that was actually loaded into your application classpath; I suspect that you were previously testing with an old version, and recently updated the POM? You were previously using version 3.2.0.

How do I know this?

I started digging through the code, and at version 3.6.0, the error message you provided is nowhere near line 203. And also, you can see that the above linked code has support for the +srv.

Browing back through previousl releases, I finally found that error massge on line 203, back at release 3.2.0.

Long story short, trying doing a Maven clean, and rebuild.

Relaunch Eclipse to pick up new dependencies if a project refresh does not help.

Second

MongoTimeoutException: Timed out after 30000 ms while waiting for a server

This one is highly likely a firewall / access control group configuration issue, in that the firewall is blocking the packets from reaching your Atlas cluster.

See adding addresses to the whitelist.

Matt Clark
  • 27,671
  • 19
  • 68
  • 123
  • Thank you, Matt for a detail answer! Yes, I changed versions a lot of time, but the issue is the same. I will check your link, and now trying to understand why I get the first error with "mongodb+srv", because I originally used version 3.6. – invzbl3 Jun 20 '18 at 09:40
  • According to the error posted, version 3.2.0 was the one loaded onto the classpath. You are getting these dependencies from Maven? Try to delete your `~/.m2` directory, and rebuild, this will cause all artifacts to be re-downloaded. Try inspecting your classpath to view the jars actually loaded. – Matt Clark Jun 20 '18 at 16:53
  • Yes, this dependency is for maven, using POM file. I tried to connect from IDE Eclipse and here is something like: `INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}`, but then appears second issue too. – invzbl3 Jun 20 '18 at 21:03
  • Matt Clark, second issue is happend, when I tried to add information to my database in cluster. But I see that my db is added not in cluster, but to this local address (I see that when running mongo process): mongodb://127.0.0.1:27017, but specified the path to the cluster in the code. I have M0 (Free Tier) cluster. – invzbl3 Jun 20 '18 at 23:37
  • If I run local address instead of cluster, I get : `"com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketReadTimeoutException: Timeout while receiving message}, caused by {java.net.SocketTimeoutException: Read timed out}}]"` – invzbl3 Jun 20 '18 at 23:38
2

One more important note: in this string:

MongoClientURI uri = new MongoClientURI("mongodb+srv://admin:mypassword@cluster0-ox90k.mongodb.net/test?retryWrites=true");

test ==> is a Db name, before making this connection, DB should exist.

Pankaj Kumar Katiyar
  • 1,474
  • 1
  • 20
  • 36
2

The above-mentioned solution is not working in the current assignment, because I'm working on the Spring-boot framework assignment.

I have got error as Caused by: java.net.UnknownHostException: khweshacluster0.brzta.mongodb.net

To Solve this I have to take configurations from below

enter image description here

Take Highlighted URL & make below format URL as

spring.data.mongodb.uri=mongodb://:@<Atlas_cluster_URL>

& same update in application.properties as follows,

spring.data.mongodb.uri=mongodb://username:password@khweshacluster0-shard-00-00.brzta.mongodb.net:27017,khweshacluster0-shard-00-01.brzta.mongodb.net:27017,khweshacluster0-shard-00-02.brzta.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-3b1nqz-shard-0&authSource=admin&retryWrites=true&w=majority

ChrisF
  • 134,786
  • 31
  • 255
  • 325
Mahesh More
  • 151
  • 7
0

I faced same issue when trying to connect from my tomcat application to MongoDB. I had tomcat 9.0 and MongoDB 4.2 installed with application using Mongo Driver 3.12.3

Error: org.springframework.dao.DataAccessResourceFailureException: Timed out after 
30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, 
servers=[{address=@127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception=
{com.mongodb.MongoSocketException: @127.0.0.1}, caused by 
{java.net.UnknownHostException: @127.0.0.1}}]; nested exception is 
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect.
 Client view of cluster state is {type=UNKNOWN, servers=[{address=@127.0.0.1:27017, 
type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: 
@127.0.0.1}, caused by {java.net.UnknownHostException: @127.0.0.1}}]

I tried creating sample Java application to connect DB and it worked, however it was not able to connect from web application.

So created user for DB and assigned role userAdmin, which worked for me.

Not working Conn String - mongodb://@127.0.0.1:27017/docs <br>
Working Conn string -     mongodb://docs_local:docs@127.0.0.1:27017/docs
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35
0

i had this issue and i checked the documentation i created a configuration class like this

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    public @Bean
    MongoClient mongoClient() {
        return MongoClients.create("mongodb://localhost:27017");
    }
}

you can put your uri where "mongodb://localhost:27017" is

https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#reference

0

I had the similar issue and solved it by selecting Node driver version 2.2.12 or later and it will give me a connection string starting with 'mongodb://'

Jason Huang
  • 179
  • 1
  • 3