2014-10-31 40 views
0

我有这样的实体。MongoDB和Spring数据。在实体中获取数组的大小

@Document 
public class Entity{ 
    @Id 
    private String id; 
    private Set<Integer> ids; 
} 

我需要得到数组的大小IDS

如何可以使用Spring的数据聚合框架来完成?

我想是这样的:

AggregationOperation match = Aggregation.match(where("id").is(id)); 
AggregationOperation group = Aggregation.group("ids"); 
Aggregation aggregation = Aggregation.newAggregation(match, group); 
template.aggregate(aggregation, Entity.class, Entity.class); 

好像我这样做完全错误的。

回答

0

我已经找到了解决方案!

Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(match), 
       Aggregation.project("ids"), Aggregation.unwind("ids"), Aggregation.group().count().as("count")); 

现在,它工作正常,没有获得数组中的所有项目。

UPD:这是一个更好的

Aggregation aggregation = Aggregation.newAggregation(
       Aggregation.match(where("id").is(id)), 
       Aggregation.project().and("ids").project("size").as("count")); 
+1

不客气 – AknKplnoglu 2014-11-04 10:49:30

0

你可以这样使用;

Aggregation aggregation = newAggregation(match(criteria),group("ids").count().as("count")); 

这将产生:

{"yourPOJO":[{"ids":[...],"count":5},...]} 
+0

谢谢回答。但它产生我{“myPojo”:[{“ids”:[...],“count”:1,},...]} 它是正确的行为,因为它计数多少这样的元素, “,而不是他们存在多少元素。 – Shatranaft 2014-11-04 09:00:04

0

那么你可以使用

Aggregation aggregation = newAggregation(match(criteria),group("ids").count().as("count"),unwind("ids"),group("ids._id").count().as("count1")); 
+0

谢谢。这不是正确的解决方案,但它帮助我找到正确的解决方案。 – Shatranaft 2014-11-04 10:41:48