Mongo DB根据关键字段查找具有最高价值的所有记录

时间:2019-02-15 16:05:29

标签: mongodb mongodb-query aggregation-framework

我想为集合中的每个用户获取具有最高价值的记录的注释。

PlayerProfile

将给出以下结果:

//myCol
[
    {'user' : 1, 'value':20, "comment": "cloudy", "date":"2018-12-01"},
    {'user' : 2, 'value':5, "comment": "sun","date":"2018-12-01"},
    {'user' : 3, 'value':13, "comment": "rain","date":"2018-13-01"},
    {'user' : 4, 'value':13, "comment": "cloudy","date":"2018-13-01"},
    {'user' : 2, 'value':20, "comment": "rain","date":"2018-01-20"},
    {'user' : 1, 'value':2, "comment": "cloudy","date":"2018-02-02"},
]

在MySQL中,我将使用一些联接逻辑

//Result 
[
    {'user' : 1, 'value':20, "comment": "cloudy", "date":"2018-12-01"},
    {'user' : 2, 'value':20, "comment": "rain","date":"2018-01-20"},
    {'user' : 3, 'value':13, "comment": "rain","date":"2018-13-01"},
    {'user' : 4, 'value':13, "comment": "cloudy","date":"2018-13-01"},
]

但是,对于Mongo,这种逻辑似乎并不存在。

我尝试通过首先获取每个用户的最大值将代码分成两部分:

SELECT user FROM myTable as t0
LEFT JOIN (SELECT user, max(value) as maxVal from myTable ) t1 on t0.user = t1.user and t0.value = t1.maxVal
WHERE maxVal IS NOT NULL

为此,我正在努力寻找使用max_list = myCol.aggregate( [ { "$group": { "_id": "$user", "maxValue": { "$max": "$value" } } }, { "$project" : { "user" : "$_id", "maxValue":"$maxValue", "_id":0 } } ] ) ==> [{'user':1, 'maxValue':20}...] 函数的好方法,尤其是善用find来获得仅与{{1 }}

3 个答案:

答案 0 :(得分:2)

可以,但是方法略有不同:

db.myCol.aggregate([
    {$sort: {value:-1}},
    {$group:{
        _id: "$user",
        doc: {$first: "$$ROOT"}
    }},
    {$replaceRoot: {newRoot: "$doc"} }
])

答案 1 :(得分:1)

您可以通过value $sort$group将文档$first应用于http://apoiarmais.com/teste/paises.php

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
        }
    }
])

答案 2 :(得分:1)

您甚至只能使用两个阶段

before-the-data

$max始终采用在对象内部传递的第一个表达式的最大值。这里是db.collection.aggregate([ { "$group": { "_id": "$user", "doc": { "$max": { "value": "$value", "user": "$user", "comment": "$comment", "date": "$date" } } }}, { "$replaceRoot": { "newRoot": "$doc" }} ])