0

I have simple java program that tries to connect to my only mongodb local instance and I want to insert some data. I have these referenced jar files when running the code:

 - C:\Users\olgad\Downloads\jsoup-1.11.2.jar
 - C:\Users\olgad\Downloads\mongodb-driver-3.6.1.jar
 - C:\Users\olgad\Downloads\bson-3.0.4.jar
 - C:\Users\olgad\Downloads\java-json.jar\java-json.jar
 - C:\Users\olgad\Downloads\mongo-java-driver-2.9.1.jar\mongo-java-driver-2.9.1.jar
 - C:\Users\olgad\Downloads\mongodb-driver-core-3.0.1.jar

My mongodb version is 3.4.10

public class Main {
    public static void main(String[] args) throws IOException {
        try {                       
            MongoClient mongoClient = new MongoClient("localhost",27017);

            DB database = (DB) mongoClient.getDatabase("test"); 
            DBCollection collection = database.getCollection("myCol");

            DBObject dbObject = (BasicDBObject) JSONObject.stringToValue("{'name':'mkyong', 'age':30}");
            collection.insert(dbObject);
        } catch(Exception ex) {
            // Prints what exception has been thrown
            System.out.println(ex.getMessage());
        }    
    }
}

The error that is printed is:

Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/DBRefCodecProvider at com.mongodb.MongoClient.(MongoClient.java:89) at prvCrawler.Main.main(Main.java:30)

Thanks in advance! Olga

2
  • 1
    You should try using Maven/Gradle, not manually listing JAR files Commented Jan 26, 2018 at 13:28
  • can you explain it a little more detailed? Commented Jan 26, 2018 at 13:42

1 Answer 1

1

You have one too many jars with conflicting packages. Remove all the mongodb related jars first and start over.

You have two options:

Manually downloading the jar ( Use one of the below option ). Use same versions for all jars.

  1. Download the mongo-java-driver uber jar which contains all the necessary libraries packaged as one.

  2. Download the jars (mongodb-driver, mongodb-driver-core, and bson) individually.

Use Maven/Gradle for downloading the jars.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, that solved my problem, I downloaded them manually!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.