在Golang的Mongo正中手术

14ifxucb  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(93)

我在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行的评分中位数。我也不知道该怎么做。帮帮忙,谢谢

sg2wtvxw

sg2wtvxw1#

$limit阶段之后,mongodb 7.0版的一个选项是使用$median累加器$group

groupgStage := bson.D{{"$group", bson.D{
  {"_id", 0}, 
  {"median", bson.D{{"$median", 
    bson.D{{"$input", "$rating"}, {"method", "approximate"}}
  }}}
}}}

对于旧版本,您可以

  1. $sortrating
  2. $group$push将所有rating都添加到一个数组中(在您限制后,所有5个)
  3. $project数组中间的元素
    它看起来像这样:
sortRatingStage := bson.D{{"$sort", bson.D{{"rating", 1}}}}
groupStage := bson.D{{"$group", bson.D{{"_id", 0}, {"ratings", bson.D{{"$push", "ratings"}}}}}}
projectStage := bson.D{{"$project", bson.D{
  {"_id", 0}, 
  {median, bson.D{{"$arrayElemAt", bson.D{
    {"$ratings", bson.D{{"$floor", bson.D{
      {"$divide", bson.A{{bson.D{{"$size", "$ratings"}}, 2}}}
    }}}}
  }}}}
}}}}

相关问题