mongodb-如何用最大值提取字段



我有一个mongodb collection genre_count as

user | genre         | count
-----+---------------+-------
1    | Western       | 2
1    | Adventure     | 1
1    | Comedy        | 5
2    | Western       | 3
2    | Thriller      | 1
2    | Romance       | 2

我需要为每个用户提取最大计数的类型,即用户1,最大计数的类型是喜剧 count> Count 5。我尝试使用几个如:

db.genre_count.aggregate([
  {
  $group:{
     _id:{
        user:"$user",
        genre:"$genre"
     },
     max_val:{
         $max: "$count"
     }
   }
 }
])

我以为这会起作用,但它返回了每种类型的用户计数,因此基本上它将我所有记录都归还了。

然后,我尝试了另一个解决方案,该解决方案部分工作:

db.genre_count.aggregate([
  {
  $group:{
     _id:{
        user:"$user"
     },
     max_val:{
         $max: "$count"
     }
   }
 }
])

,但这仅返回最大值,因为它没有相应的流派信息,即该最大值。有什么办法可以得到所需的结果?

要返回最大计数和流派列表,您需要在组阶段使用$max来返回每个组的最大"计数",然后使用$push累加器操作员返回每个组的"流派名称"one_answers"计数"。

从那里您需要在$project阶段使用$map操作员,以返回最大计数列表。这里的$cond用于将每个类型计数与最大值进行比较。

db.genre_count.aggregate([
        { '$group': {
            '_id': '$user', 
            'maxCount': { '$max': '$count' }, 
            'genres': { 
                '$push': {
                    'name': '$genre', 
                    'count': '$count' 
                }
            }
        }}, 
        { '$project': { 
            'maxCount': 1, 
            'genres': { 
                '$setDifference': [
                    { '$map': {
                        'input': '$genres', 
                        'as': 'genre', 
                        'in': {
                            '$cond': [
                                { '$eq': [ '$$genre.count', '$maxCount' ] }, 
                                '$$genre.name', 
                                false
                            ]
                        }
                    }}, 
                    [false]
                ]
            }
        }}
    ])

我认为您可以使用此汇总:

db.genre_count.aggregate([
{
    $sort: {user:1, count:1}
},
{
    $group: 
    { 
        _id: "$user", 
        maxCount: {$max: "$count"}, 
        genre: {$last: "$genre"} 
    }
}])

最新更新