java - 无法在聚合中使用过滤器bsons : Can't find a codec for class com. mongodb.client.model.Filters$AndFilter

标签 java mongodb

我正在尝试使用过滤器提供的 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/

相关文章:

java - 需要帮助减少 Eclipse 和 tomcat 内存使用

node.js - 在变量中检索 count mongodb 集合的值

mongodb - MongoDB中的SQL View

mongodb - Grails + Mongodb + Spock:执行嵌入式字段查询时抛出NullPointerException

mongodb - 不在 sails 的吃水线 ORM 中

java - 在 Selenium WebDriver 中打开新选项卡后,如何使其成为浏览器中的可见/Activity 选项卡?

java - 每当我打开 Firefox 时,让我的计算机提示我预定的问题

java - java中如何统计以大写字母开头的单词?

mongodb - 使用 $or 和 $regex 的 PyMongo find() 查询

java - 为什么 android ImageAdapter 不延迟加载图像?