不能合计使用Filters bson:找不到com.mongodb.client.model.Filters $ AndFilter类的编解码器

时间:2018-09-26 15:26:39

标签: java mongodb

我正在尝试使用过滤器提供的Bson在聚合管道中使用它们 我得到了例外,因为显然是聚合尝试对Bsons进行序列化,而Filters Bsons无法进行序列化。

我遇到了类似这样的异常。

  

找不到类com.mongodb.client.model.Filters $ OperatorFilter的编解码器

     

找不到类com.mongodb.client.model.Filters $ AndFilter的编解码器

我不能简单地将Filters.eq(key, val)替换为new Document("$eq", new Document(key, val)),因为我已经有很多使用过滤器的代码。

我的代码如下:

// In my real code, the Filters:OperatorFilter object comes from 
// the REST interface through several layers of code, but any Bson 
// from Filters will cause the exception 
Bson filter = Filters.eq("key", "value");

// then build the pipeline
List<Bson> operations = new ArrayList<>();

// First we reduce the scope to the visibility
// !!! This is the part of the pipeline that is problematic
if (filter != null) {
    operations.add(new Document("$match", filter)); 
}

// We group the documents by the property
Document groupFields = new Document("_id", "$" + property);
// ... don't forget to calculate the group size
groupFields.put("count", new Document("$sum", 1));
operations.add(new Document("$group", groupFields));

// We sort on the count first and then on the value
Document sort = new Document("count", -1);
sort.put("_id", 1);
operations.add(new Document("$sort", sort));
// ... and get only the biggest ones
if (limit > 0) {
     operations.add(new Document("$limit", limit));
}

// !!! the call to aggregate raises the exception
AggregateIterable<Document> groups = this.collection.aggregate(operations);

产生异常的一种非常简单的方法就是尝试序列化Filters:OperatorFilter对象。例如:

Bson bson = Filters.eq("key", "value")
ObjectMapper mapper = new ObjectMapper()
mapper.writeValueAsString(bson)

我曾考虑过使用Bson:toBsonDocument,但是现在我不知道如何简单地获取它需要作为参数的CodecRegistry。

该项目是使用mongo-java-driver 3.4.1编译的,但我也使用最新的3.8.2进行了测试,但未成功。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在编写聚合管道时,请使用Aggregations工厂方法,而不要将其编写为Document。 (使用过滤器工厂过滤器的方式相同)

文档位于: http://api.mongodb.com/java/current/com/mongodb/client/model/Aggregates.html

将这些语句替换为:

new Document("$match", filter)
new Document("$group", groupFields)
new Document("$sort",  sort)

这些:

Aggregates.match(filter)
Aggregates.group(groupFields)
Aggregates.sort(sort)