![](/img/trans.png)
[英]How do I add a $comment to a distinct or aggregate call using the Java driver for mongodb?
[英]How to do aggregate query with accumulators using mongodb driver in java
我在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的编解码器
因此,要恢复并使其更具可读性和全面性,我所要求的是:
在此先感谢您,如果您需要更多信息,我准备提供它们。
您对api的使用不正确。
将您的汇总更改为以下(坚持使用Document
表达式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
是一个帮助程序类,主要用于为Accumulators
提供数据保存器,该Accumulators
返回key
和Bson
值对。 因此,它并不打算用作值类型。 与辅助方法一起使用时,它将转换为Document
并使用Document Codec进行序列化。
您可以重新整理聚合以使用辅助方法( Filters
, Projections
Accumulators
和Aggregates
)
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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.