![](/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.