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

后端 未结 3 649
春和景丽
春和景丽 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:13

    You can even do with two stages only

    db.collection.aggregate([
      { "$group": {
        "_id": "$user",
        "doc": {
          "$max": {
            "value": "$value",
            "user": "$user",
            "comment": "$comment",
            "date": "$date"
          }
        }
      }},
      { "$replaceRoot": { "newRoot": "$doc" }}
    ])
    

    $max always takes the maximum value of the first expression which is passed inside the object. Here it is value.

    0 讨论(0)
  • 2020-12-11 09:31

    It does, but the approach is slightly different:

    db.myCol.aggregate([
        {$sort: {value:-1}},
        {$group:{
            _id: "$user",
            doc: {$first: "$$ROOT"}
        }},
        {$replaceRoot: {newRoot: "$doc"} }
    ])
    
    0 讨论(0)
  • 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
            }
        }
    ])
    
    0 讨论(0)
提交回复
热议问题