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")
);
什麼是文檔的等效Java模型? – nullpointer
用模型更新了問題。 – danial
嘗試'Aggregation agg = Aggregation.newAggregation( match(Criteria.where(「tags」)。in(「leather」)), group()。avg(「price」)。as(「averagePrice」) ) ;' – Veeram