LoGWRiTer
LoGWRiTer

Reputation: 129

MongoDB Java Driver MongoClient does not working when running

I tried to use MongoDB java driver on Ubuntu 14.04.

The program indeed can pass the compile stage, but when running, it just has this error:

Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/MongoClient
    at App.main(App.java:23)
Caused by: java.lang.ClassNotFoundException: com.mongodb.MongoClient
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 1 more

My Java version is 1.7, and I indeed tried 1.6, but same error happened. My compile command is:

javac App.java -classpath mongo-java-driver-2.13.0.jar

And I run the program using command:

java App

Below is my Java code:

import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteOperation;
import com.mongodb.BulkWriteResult;
import com.mongodb.Cursor;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ParallelScanOptions;
import com.mongodb.MongoException;
import com.mongodb.ServerAddress;

import java.util.List;
import java.util.Set;

public class App
{
    public static void main(String[] args)
    {
        System.out.println("----- Program Start -----");
        try {
            MongoClient mongoClient = new MongoClient("localhost" , 27017);
            DB db = mongoClient.getDB("demo");
            System.out.println("Connect to database successfully.");

            DBCollection coll = db.getCollection("test");
            BasicDBObject doc = new BasicDBObject();
            for(int i = 0; i < 10; i++) {
                doc.append("A" + Integer.toString(i), 12.56);
            }

            System.out.println(doc);
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": ");
            e.getMessage();
        }
    }
}

Could anyone please help? Thanks!!

Upvotes: 1

Views: 9877

Answers (1)

The classpath is needed for both the compilation and the execution. The following invocation should work

java App -classpath mongo-java-driver-2.13.0.jar

Upvotes: 2

Related Questions