简体   繁体   English

bson无法转换为DBObject

[英]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 我正在尝试查询mongodb,如官方文档页面上的示例所示,但它在Netbeans上给了我以下错误

bson cannot be converted to DBObject bson无法转换为DBObject

Here is the code 这是代码

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

// Now connect to your databases
DB db = mongoClient.getDB("webAppDB");
System.out.println(db.getCollectionNames());
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 该示例的链接
http://mongodb.github.io/mongo-java-driver/3.2/driver/getting-started/quick-tour/ http://mongodb.github.io/mongo-java-driver/3.2/driver/getting-started/quick-tour/

You use DBCollection where method find() has signature DBCursor find(DBObject query) , so you should pass DBObject as its argument. 您可以使用DBCollection ,其中方法find()具有签名DBCursor find(DBObject query) ,因此您应该传递DBObject作为其参数。

Whereas eq() method is defined in Filters and has signature <TItem> Bson eq(String fieldName, TItem value) , so it returns Bson type, not DBObject . 而eq()方法是在Filters中定义的,并且具有签名<TItem> Bson eq(String fieldName, TItem value) ,因此它返回Bson类型,而不是DBObject类型。

To pass Bson type to find() method you should use MongoCollection , (where find() is FindIterable<TDocument> find(Bson filter) ), not DBCollection . 要将Bson类型传递给find()方法,您应该使用MongoCollection ,(其中find()是FindIterable<TDocument> find(Bson filter) ),而不是DBCollection

MongoCollection is newer, since it's available after v3.0 release. MongoCollection是较新的,因为它在v3.0版本之后可用。 Thus, maybe you would like to stick with it, instead of DBCollection . 因此,也许您想坚持使用它,而不是DBCollection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM