我正在尝试使用过滤器提供的 Bson 在聚合管道中使用它们 我收到异常,因为显然聚合尝试序列化 Bson,而过滤器 Bson 无法序列化。
我遇到了这样的异常。
Can't find a codec for class com.mongodb.client.model.Filters$OperatorFilter
Can't find a codec for class 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 进行了测试,但没有成功。
有什么想法吗?
最佳答案
编写聚合管道时,请使用聚合工厂方法,而不是将它们编写为文档。 (与使用过滤器工厂过滤器的方式相同)
文档可以在以下位置找到: 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)
关于java - 无法在聚合中使用过滤器bsons : Can't find a codec for class com. mongodb.client.model.Filters$AndFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52521307/