Home > Article > Backend Development > Mongo median operation in Golang
Mongo median operation in Golang is an important technology that is of great significance to developers. It allows us to be more flexible and efficient when dealing with Mongo databases. In Golang, we can use Mongo median operations to implement various data operations, such as insertion, update, and deletion. This computing method allows us to better utilize the powerful functions of Mongo and improve our development efficiency. This article will introduce the usage and precautions of Mongo median operation in Golang through practical cases to help developers better master this technology.
I have a collection in mongo (go) whose type is:
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"` }
I need to evaluate the median rating of the last 5 records (via the receivedAt
time field) of a certain user (via his user_id
).
I've got this:
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})
But I don't know how to get the median rating of these 5 rows. I'm not sure the correct way for me to do this. Help, thanks
After the $limit
stage, an option since mongodb version 7.0 is $group
with $median
Accumulator
groupgStage := bson.D{{"$group", bson.D{ {"_id", 0}, {"median", bson.D{{"$median", bson.D{{"$input", "$rating"}, {"method", "approximate"}} }}} }}}
For older versions, you can
$sort
by rating
$group
and $push
all ratings
into an array (all 5 after limiting) $project
The project in the middle of the arrayIt looks like this:
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}}} }}}} }}}} }}}}
The above is the detailed content of Mongo median operation in Golang. For more information, please follow other related articles on the PHP Chinese website!