Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to MongoDB using jdbc driver

Purpose is to connect MongoDB remote server through JAVA:

    URL = "jdbc:mongo://" + serverIP + ":"
    + port+ "/" +databaseName;                     
    Class.forName("mongodb.jdbc.MongoDriver");
    dbConn = getConnection(URL,mongo1, mongo1);

Tried Unity_trial.Jar, mongo_version.jar files but the error comes is 'mongodb.jdbc.MongoDriver' classNameNotFound.

If I comment the class.forname line, the next error is

   URL = "jdbc:mongo://" + serverIP + ":" + port
    + "/" +databaseName;

is not in correct format. Not sure about where I am making the mistake. Thanks for your help in advance.

like image 222
manoj Avatar asked Oct 24 '25 18:10

manoj


1 Answers

If you are getting a ClassNotFoundException, the issue is that the jar containing the mongodb.jdbc.MongoDriver class is not on your classpath. If you're not sure what JAR this class is in, I would reccomend getting 7-Zip so that you can inspect the contents of the jar and see for yourself if the class is there.

The correct way to connect to MongoDB with your approach is:

Class.forName("mongodb.jdbc.MongoDriver");
String URL = "jdbc:mongo://<servername>:<port>/<databaseName>";
Connection jdbcConn = DriverManager.getConnection(url,"user","pass");


But MongoDB isn't really meant to be used with JDBC, so if your requirements allow, I would reccomend getting a connection the "mongodb" way.

MongoClient client = new MongoClient("localhost");

For details on how to do it this way, see the MongoDB docs

like image 154
Andy Guibert Avatar answered Oct 26 '25 08:10

Andy Guibert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!