2017-07-06 148 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

相关问题