0
votes

I am trying to connect to a Mongodb database using Java.I have added the following dependencies to my project in eclipse:

bson-3.0.1.jar
mongodb-driver-core-3.0.1.jar
mongodb-driver-3.0.1.jar

Here is the code snippet I have written to connect to mongodb:

public void connectToDB()
{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "messenJ" );
System.out.println("Connected to database successfully");
} 

However , I am getting following error after I run my code:

java.lang.NoSuchMethodError: com.mongodb.ReadPreference.primary()Lcom/mongodb/ReadPreference;

How can I fix this problem?
Thanks.

1

1 Answers

1
votes

You should rather download a newer version of the MongoDB Java Driver here. It includes the latest Bson version aswell!

The API changed too:

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongoClient.getDatabase("yourDatabase");

(See: http://mongodb.github.io/mongo-java-driver/3.3/driver/getting-started/quick-tour/)

Hope this helps a bit :)