I'm trying to connect java project to my mongodb database. But I keep recieving this error although I imported the mongodb driver to the project:
Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/internal/connection/ServerAddressHelper
and that's my connection code:
MongoClient mongoClient = new MongoClient(new
MongoClientURI("mongodb://localhost:27017"));
MongoDatabase database = mongoClient.getDatabase("Etudiant");
MongoCollection collection = database.getCollection("EtudiantC");
System.out.println("connected!");
解决方案
The NoClassDefFoundError exception tells you that the class was there when the code you run was compiled, but it is missing in your application's classpath now.
The most probable explanation is that you did add the mongodb-driver.jar to your classpath, but forgot about adding its transitive dependencies as well. The reported missing class ServerAddressHelper is present inside the mongodb-driver-core.jar.
So how to solve this problem? Either use a dependency management system like Maven or Gradle for automatically downloading all the necessary jar-s, or you need to do this by other means (e. g. manually). It seems like you may also use the all-in-one mongo-java-driver.jar instead - see project's official documentation for details (search for "Binaries" on the page).