Mongo DB find all records with highest value depending on a key field

后端 未结 3 657
春和景丽
春和景丽 2020-12-11 09:05

I would like to get for each user in my collection the comment of the record with the highest value.

//myCol
[
    {\'user\' : 1, \'value\':20, \"comment\":          


        
3条回答
  •  忘掉有多难
    2020-12-11 09:33

    You can $sort your documents by value before applying $group with $first

    db.myCol.aggregate([
        { 
            $sort: { value: -1 }
        },
        {
            $group: {
                _id: "$user",
                value: { $first: "$value" },
                comment: { $first: "$comment" },
                date: { $first: "$date" }
            }
        },
        {
            $sort: { _id: 1 }
        },
        {
            $project: {
                user: "$_id",
                _id: 0,
                value: 1,
                comment: 1,
                date: 1
            }
        }
    ])
    

提交回复
热议问题