DevOps | Cloud | Analytics | Open Source | Programming





How To Fix - Database Access Error in MongoDB ?



This Post explains - How To Fix - Database Access Error in MongoDB. Sometimes (if you are using older versions of MongoDB while the source code uses latest version systax , you might face issue while connecting Database Objects. We will discuss one such example below.

Issue:


  • During execution of the code at the time of Database Access , you get the below error -


"Error:(21, 51) java: incompatible types: com.mongodb.DB cannot be converted to com.mongodb.client.MongoDatabase"


 

Reason:


  • Most likely you are not using the Updated MongoDB java driver.
  • Maybe you are using getDB() Function (Old) insetad of  getDatabase() Function (New)
 

Fix :


  • Update the mongo-java-driver to the latest version .
  • The latest version uses getDatabase()" Function to access Database Objects. See Example below -
The below piece of code is taken from MongoDB Official Documentation - https://docs.mongodb.com/manual



final MongoClient client = MongoClients.create(uri);

/\*
Prereq: Create collections. CRUD operations in transactions must be on existing collections.
\*/

client.**getDatabase**("mydb1").getCollection("foo")
      .withWriteConcern(WriteConcern.MAJORITY).insertOne( new Document("abc", 0));

client.**getDatabase**("mydb2").getCollection("bar")
.withWriteConcern(WriteConcern.MAJORITY).insertOne( new Document("xyz", 0));


Hope this Post helps you To Fix - Database Access Error in MongoDB  

Additional Read -