2017-07-06 75 views
0

我在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表示是否正確?
  • 如果是這樣,爲什麼我無法打印或訪問查詢結果?

在此先感謝您,如果您需要更多信息,我已準備好提供它們。

回答

1

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主要是建爲Accumulators其返回keyBson值對提供數據的持有人一個輔助類。所以它並不意味着被用作值類型。使用輔助方法時,它將轉換爲Document並使用文檔編解碼器進行序列化。

您可以返工您彙總使用輔助方法(FiltersProjectionsAccumulators & 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/

+0

你寫是不行的,在東陽$ addToSet的解釋失敗的第一個集合。但其他人都很完美,所以非常感謝幫助我!我將在使用聚合器時使用這種方法。 – Mirko

相關問題