2017-08-27 211 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