我在MongoDB及其与java的交互方面很新颖。 我使用这个驱动程序如何在java中使用mongodb驱动程序进行聚合查询
<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表示是否正确?
- 如果是这样,为什么我无法打印或访问查询结果?
在此先感谢您,如果您需要更多信息,我已准备好提供它们。
你写是不行的,在东阳$ addToSet的解释失败的第一个集合。但其他人都很完美,所以非常感谢帮助我!我将在使用聚合器时使用这种方法。 – Mirko