How to Use Go With MongoDB For Group?

124 Views Asked by At

data

userId   height 

curry      1
 
curry      2

kd         3


kd         4

james      2

input: userIds=[curry,kd,james]

i want


curry      2

kd         4

james     2

So, i want one record with the highest height in each group.

1

There are 1 best solutions below

1
wuqinqiang On

Get!!!!

but I don't understand.

$sort must definition before $group , if not, the height is not the largest.

Why? Or i was wrong ?

users := []string{"curry", "kd", "james"}
    pipe := mongo.Pipeline{
        {
            {Key: "$match", Value: bson.D{{Key: "userId", Value: bson.M{"$in": users}}}},
        },

        {
            // must before $group
            {Key: "$sort", Value: bson.D{{Key: "height", Value: -1}}},
        },
        {
            {Key: "$group",
                Value: bson.D{
                    {Key: "_id", Value: "$userId"},
                    {Key: "height", Value: bson.D{{Key: "$first", Value: "$height"}}},
                },
            },
        },

        //don't work !!!!!.the height is not the largest
        //{
        //  {Key: "$sort", Value: bson.D{{Key: "height", Value: -1}}},
        //},
    }