我对 MongoDB 及其与 java 的交互还很陌生。 我正在使用这个驱动程序
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
我想执行这个聚合查询:
db.getCollection('COLLECTION').aggregate(
[
{"$match":{"val.elem.0001":{"$exists":true}}},
{"$project":{"FIELD_PATH":"$val.elem.0001"}},
{$group:{_id:{"FIELD":{"$literal":"0001"}},
"PATH":{"$addToSet":"$FIELD_PATH"}}}
]
);
我编写的java代码如下(但是我不确定我是否正确使用了addToSet方法):
AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
new Document("$match", new Document("val.elem.0001",new Document("$exists",true))),
new Document("$project", new Document("FIELD_PATH","$val.elem.0001")),
new Document("$group", new Document("_id",new Document("FIELD", new Document("$literal", "0001"))
.append("PATH", Accumulators.addToSet("$PATH", "$FIELD_PATH"))))));
这是正确的吗?因为如果添加“附加”部分,我无法在屏幕上打印结果。返回的错误是 找不到 com.mongodb.client.model.BsonField 类的编解码器
因此,为了恢复并使我所要求的内容更具可读性和更全面性:
- 查询的 Java 表示形式是否正确?
- 如果是这样,为什么我无法打印或访问查询结果?
提前致谢,如果您需要更多信息,我已准备好提供。
最佳答案
您使用的 api 不正确。
将聚合更改为以下内容(坚持使用 Document
作为表达式)
AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
new Document("$match", new Document("val.elem.0001",new Document("$exists",true))),
new Document("$project", new Document("FIELD_PATH","$val.elem.0001")),
new Document("$group", new Document("_id",new Document("FIELD", new Document("$literal", "0001"))).append("PATH", new Document("$addToSet", "$FIELD_PATH")))));
BsonField
是一个帮助程序类,主要为返回 key
和 Bson
值的 Accumulators
提供数据持有者一对。因此它不适合用作值类型。与辅助方法一起使用时,它会转换为 Document
并使用文档编解码器进行序列化。
您可以重新设计聚合以使用辅助方法(过滤器
、投影
累加器
和聚合
)
AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
Aggregates.match(Filters.exists("val.elem.0001")),
Aggregates.project(Projections.computed("FIELD_PATH","$val.elem.0001")),
Aggregates.group( new Document("FIELD", new Document("$literal", "0001")), Accumulators.addToSet("PATH", "$FIELD_PATH"))));
您可以通过使用静态导入进一步减少聚合。
import static com.mongodb.client.model.Accumulators.addToSet;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.match;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.computed;
import static java.util.Arrays.*;
AggregateIterable<Document> output = collection.aggregate(asList(
match(Filters.exists("val.elem.0001")),
project(computed("FIELD_PATH","$val.elem.0001")),
group( new Document("FIELD", new Document("$literal", "0001")), addToSet("PATH", "$FIELD_PATH"))));
了解更多信息
http://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/aggregation/
关于java - 如何在java中使用mongodb驱动程序使用累加器进行聚合查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44959054/