Spring数据mongodb聚合函数无法使用spring-data-mongodb的1.3.5-RELEASE

时间:2014-08-07 08:01:34

标签: java spring mongodb spring-data spring-data-mongodb

我需要使用包含nexted数组数组的spring数据来过滤mongodb中的文档。我在mongo shell上使用以下聚合查询,它工作正常。 但是当我通过springdata聚合操作解雇时,我得到空的响应。 工作mongo查询是:

db.searchResource.aggregate({$match:{"_id" : ObjectId("53cf4e3dae92ac6561807f6d")}},{$project:{"rssSearchResponse.journeys":1}},{$unwind : "$rssSearchResponse.journeys"},{$match:{"rssSearchResponse.journeys.stops":0}});

我正在使用的弹簧数据代码并且无法正常工作:

TypedAggregation<SearchResource> aggregation = Aggregation.newAggregation(SearchResource.class, Aggregation.match(new Criteria("_id").is(new ObjectId(searchId))),
                Aggregation.project("rssSearchResponse.journeys"),
                Aggregation.unwind("rssSearchResponse.journeys"),
                Aggregation.match(new Criteria("rssSearchResponse.journeys.stops").is(0))
                );
AggregationResults<SearchResource> result = mongoOperations.aggregate(aggregation, JourneyInformation.class);

我试过打破这个聚合函数,它能够投射rssSearchResponse.journeys但是在$ unwind之后它会返回空结果。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

怎么样:

@Test
public void foo() {

    mongoTemplate.dropCollection(RssSearchResponse.class);

    RssSearch rs = new RssSearch();
    rs.id  = "123";
    rs.rssSearchResponse = new RssSearchResponse(
            new Journey[] {new Journey("A", 1),new Journey("B", 0),new Journey("C", 0),new Journey("D", 1)}
    );

    mongoTemplate.insert(rs);

    Aggregation agg = newAggregation(RssSearch.class, //
          match(where("_id").is(rs.id)) //
        , project("rssSearchResponse.journeys") //
        , unwind("journeys") //
        , match(where("journeys.stops").is(0)) //
    );

    AggregationResults<DBObject> result = mongoTemplate.aggregate(agg, RssSearch.class, DBObject.class);
    System.out.println(result);

}

static class RssSearch{
    String id;
    RssSearchResponse rssSearchResponse;
}

static class RssSearchResponse{
    Journey[] journeys;

    public RssSearchResponse(Journey[] journeys) {
        this.journeys = journeys;
    }
}

static class Journey{
    String name;
    int stops;

    public Journey(String name, int stops) {
        this.name = name;
        this.stops = stops;
    }
}

这将返回B和C.

我们生成以下聚合命令:

{ 
    "aggregate" : "rssSearch" 
  , "pipeline" : [ 
     { "$match" : { "_id" : "123"}} 
   , { "$project" : { "journeys" : "$rssSearchResponse.journeys"}}
   , { "$unwind" : "$journeys"}
   , { "$match" : { "journeys.stops" : 0}}
  ]
}