我在mongo(go)收集的类型是:
type CreateFeedbackRequest struct {
UserID string `json:"user_id" validate:"required"`
WaybillID uint64 `json:"waybill_id" validate:"required"`
Rating int `json:"rating" validate:"required"`
Comment string `json:"comment"`
ReceivedAt time.Time `json:"received_at" validate:"required"`
}
我需要评估过去5个记录(由receivedAt
时间字段)为某些用户(由他的user_id
)评级的中值。我已经得到了这个:
matchStage := bson.D{{"$match", bson.D{{"_id", userID}}}}
sortStage := bson.D{{"$sort", bson.D{{"created_at", 1}}}}
limitStage := bson.D{{"$limit", tripsCount}}
cursor, err := r.c.Aggregate(ctx, mongo.Pipeline{matchStage, sortStage, limitStage})
但我不知道如何得到这5行的评分中位数。我也不知道该怎么做。帮帮忙,谢谢
1条答案
按热度按时间sg2wtvxw1#
在
$limit
阶段之后,mongodb 7.0版的一个选项是使用$median
累加器$group
对于旧版本,您可以
$sort
rating
$group
和$push
将所有rating
都添加到一个数组中(在您限制后,所有5个)$project
数组中间的元素它看起来像这样: