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