Salih Erikci Salih Erikci - 1 year ago 74
Java Question

bson cannot be converted to DBObject

I am trying to query a mongodb as it is shown in example on the official documentation page but it gives me the following error on Netbeans

bson cannot be converted to DBObject

Here is the code

MongoClient mongoClient = new MongoClient("localhost", 27017);

// Now connect to your databases
DB db = mongoClient.getDB("webAppDB");
System.out.println("Connect to database successfully");
DBCollection collection = db.getCollection("users");
Document myDoc = collection.find(eq("i", 71)).first(); // Error Line

The link to the example

Answer Source

You use DBCollection where method find() has signature DBCursor find(DBObject query), so you should pass DBObject as its argument.

Whereas eq() method is defined in Filters and has signature <TItem> Bson eq(String fieldName, TItem value), so it returns Bson type, not DBObject.

To pass Bson type to find() method you should use MongoCollection, (where find() is FindIterable<TDocument> find(Bson filter)), not DBCollection.

MongoCollection is newer, since it's available after v3.0 release. Thus, maybe you would like to stick with it, instead of DBCollection.