2017-08-27 125 views
1

比方说,我有一个集合items,这些都是这个集合中的数据:MongoDB的春天数据合计平均

{ 
    "_id": 1 
    "tags": ["handbag", "women", "leather"] 
    "price": 30 
}, { 
    "_id": 2 
    "tags": ["jewelry", "women", "necklace"] 
    "price": 40 
}, { 
    "_id": 3 
    "tags": ["men", "leather", "necklace"] 
    "price": 10 
} 

与Java模型

class Item { 
    public ObjectId id; 
    public List<String> tags; 
    public int price; 
} 

我如何获得的平均价格标有leather的商品?

我知道,从MongoDB的CLI我能得到这样的:

db.items.aggregate([ 
    { $match: { tags: { $in: ["leather"] } } }, 
    { $group: { _id: null, averagePrice: { $avg: "$price" } } } 
]) 

但我怎么能转换成Java春天开机/数据的代码呢? Aggregation.group()方法只接受我无法指定的字段的名称_id: null,因此它会将所有匹配的元素分组为一个组。

这里是在Java中,聚集查询

Aggregation.newAggregation(
    match(Criteria.where("tags").in("leather")), 
    group("_id") // how to group all matching rows in one group. 
       .avg("price").as("averagePrice") 
); 
+0

什么是文档的等效Java模型? – nullpointer

+0

用模型更新了问题。 – danial

+1

尝试'Aggregation agg = Aggregation.newAggregation( match(Criteria.where(“tags”)。in(“leather”)), group()。avg(“price”)。as(“averagePrice”) ) ;' – Veeram

回答

0

在Java中,相关的代码应该是有点像:

collection.aggregate(
    Arrays.asList(
     Aggregates.match(Filters.eq("tags", "leather")), 
      Aggregates.group("$price", Accumulators.avg("$price", "averagePrice")) 
    ) 
) 
+0

是否将它们按“价格”进行分组,使具有相同价格的要素只能计入一次? – danial