如何计算 mongoDB 和 spring 中字段的平均值。我们有 $avg() 函数供终端使用,但如何使用 mongotemplate 执行它。
例如在
db.sales.aggregate(
[
{
$group:
{
_id: "$item",
avgAmount: { $avg: { $multiply: [ "$price", "$quantity" ] } },
avgQuantity: { $avg: "$quantity" }
}
}
]
)
我们在这里计算平均值,所以我们如何使用 mongotemplate 执行它。
现在我正在使用一个函数来获得平均评分
我正在使用这样的功能..
public List getrating() {
TypedAggregation<RatingReviewModel> agg = newAggregation(RatingReviewModel.class,
group("hospitalid")
.avg("rating").as("avgrating")
);
AggregationResults<DBObject> result = operations.aggregate(agg, DBObject.class);
List<DBObject> resultList = result.getMappedResults();
return resultList;
}
但是在调试时 resultList 是 Empty 所以它什么也没返回。