[英]Can't find a codec for class com.mongodb.BasicDBObject error in Java using mondodb
I am using mongodb's async driver 3.0.2 ( http://mongodb.github.io/mongo-java-driver/3.0/driver-async/ ) with Java. 我正在使用mongodb的异步驱动程序3.0.2( http://mongodb.github.io/mongo-java-driver/3.0/driver-async/ )和Java。
I am trying to find the 10 closest documents to a place. 我试图找到一个地方最近的10个文件。 The following query I would use in a mongodb shell to accomplish this: 我将在mongodb shell中使用以下查询来完成此任务:
db.locations.find( { loc :
{ $geoWithin :
{ $centerSphere :
[ [ 40 , -40 ] , 10 / 3963.2 ]
} } } ).limit(10);
I need to though run this in java so created the query below, but when I run it I get this exception: 我需要在java中运行它,因此创建了下面的查询,但是当我运行它时,我得到了这个异常:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.mongodb.BasicDBObject.
CODE: 码:
BasicDBObject geometery = new BasicDBObject("$centerSphere", asList(
asList(40, -40), 10 / 3963.2));
BasicDBObject operator = new BasicDBObject("$geoWithin", geometery);
BasicDBObject query = new BasicDBObject("loc", operator);
Block<Document> postsBlock = new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
SingleResultCallback<Void> postsCallback = new SingleResultCallback<Void>() {
@Override
public void onResult(final Void result, final Throwable t) {
System.out.println("Operation Finished!");
}
};
try {
collection.find(query).limit(10).forEach(postsBlock, postsCallback);
} catch (Exception exc) {
exc.printStackTrace();
}
In your connection you need to specify the codec registry com.mongodb.MongoClient.getDefaultCodecRegistry()
should do fine 在你的连接中你需要指定编解码器注册表com.mongodb.MongoClient.getDefaultCodecRegistry()
应该做得很好
For the async driver 对于异步驱动程序
MongoClientSettings settings = MongoClientSettings.builder().readPreference(readPreference)
.codecRegistry(com.mongodb.MongoClient.getDefaultCodecRegistry()).socketSettings(sockSettings)
.connectionPoolSettings(connPoolSettings).credentialList(credentials))
.clusterSettings(clusterSettings).build();
LOG.info("MongoClientSettings: {}, {}, {}, {}", sockSettings, connPoolSettings, clusterSettings, credentials);
MongoClient mgc = MongoClients.create(settings);
for the normal driver 对于普通的司机
MongoClientOptions settings = MongoClientOptions.builder().readPreference(readPreference)
.codecRegistry(com.mongodb.MongoClient.getDefaultCodecRegistry()).build();
MongoClient mgc= new MongoClient(servers,credentials,settings);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.