使用mondodb无法在Java中找到类com.mongodb.BasicDBObject错误的编解码器

时间:2015-07-06 04:34:45

标签: java mongodb

我正在使用mongodb的异步驱动程序3.0.2(http://mongodb.github.io/mongo-java-driver/3.0/driver-async/)和Java。

我正在尝试找到距离地点最近的10个文件。我将在mongodb shell中使用以下查询来完成此任务:

db.locations.find( { loc : 
                  { $geoWithin : 
                    { $centerSphere : 
                       [ [ 40 , -40 ] , 10 / 3963.2 ] 
                } } } ).limit(10); 

我需要在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();
                }

1 个答案:

答案 0 :(得分:3)

在您的连接中,您需要指定编解码器注册表com.mongodb.MongoClient.getDefaultCodecRegistry()应该没问题

对于异步驱动程序

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);

为普通司机

MongoClientOptions settings = MongoClientOptions.builder().readPreference(readPreference)
    .codecRegistry(com.mongodb.MongoClient.getDefaultCodecRegistry()).build();
MongoClient mgc= new MongoClient(servers,credentials,settings);