0
votes

I am trying to connect my java project to an online mongo database. I faced some issues so I decided to first try to connect on a local mongo DB but I still have the same problem.

I am using the 3 mongodb libraries (driver,driver-async and driver-core), 3.3.0 version and the bson library, 3.2.2 version.

When I launch my 'helloworld example' , copied from here : http://www.mkyong.com/mongodb/java-mongodb-hello-world-example/

I have the following errors :

Exception in thread "main" java.lang.NoClassDefFoundError: org/bson/codecs/IterableCodecProvider at com.mongodb.MongoClient.<clinit>(MongoClient.java:84) at mainClass.main(mainClass.java:24) Caused by: java.lang.ClassNotFoundException: org.bson.codecs.IterableCodecProvider at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 2 more

Note : The example code uses a method which is now deprecated, but even by replacing the code with the new version of it (using MongoClient), I still have the same errors.

2
change your bson library to 3.2.3 version - s7vr
Do you know where I can download it ? - VinhasK
oss.sonatype.org/content/repositories/releases/org/mongodb. update all thr dependencies to 3.3.0 - s7vr

2 Answers

0
votes

Solution :

Download the last version of BSON on : https://oss.sonatype.org/content/repositories/releases/org/mongodb/bson/ or https://mvnrepository.com/artifact/org.mongodb/bson/

The code furnished in the example need to be updated : use MongoClient instead of just Mongo. Insert example code :

/**** Connect to MongoDB ****/
        String uri = <URI of your mongo DB>
        MongoClientURI mgURI = new MongoClientURI(uri);
        MongoClient mongo = new MongoClient(mgURI);
        /**** Get database ****/

        MongoDatabase dataBase = mongo.getDatabase("databaseName");
        MongoCollection<Document> userCollection = dataBase.getCollection("CollectionName");
        Document document = new Document();
        document.put("key1", value1);
        document.put("key2", "value2");
        // insert into database
        userCollection.insertOne(document);

Thanks to Veeram for his answers :)

0
votes

This is because of missing required dependency classes for CodecRegistries or CodecRegistry in the classpath. To resolve/prevent the issue, instead of adding mongodb-driver, mongodb-driver-core and bson separately, to avoid version conflict and dependency mismanagement prefer the MongoDB Java Driver uber-artifact org.mongodb:mongo-java-driver containing the legacy driver, the mongodb-driver, mongodb-driver-core, and bson

For Maven

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

For Gradle

implementation 'org.mongodb:mongo-java-driver:3.12.10'