MongoDB:按组的最高值汇总组中的文档

时间:2016-02-03 13:44:11

标签: mongodb mongodb-query

使用聚合管道,我想获得代表price的最高key的文档。

例如,拿这个集合:

[
   {
      "_id":"323232",
      "name":"Something",
      "key":"A",
      "price":"100"
   },
   {
      "_id":"157236",
      "name":"Another thing",
      "key":"B",
      "price":75
   },
   {
      "_id":"555232",
      "name":"Something or another",
      "key":"B",
      "price":78
   },
   {
      "_id":"83234",
      "name":"Something or another",
      "key":"A",
      "price":20
   }
]

期望的结果:

[
   {
      "_id":"323232",
      "name":"Something",
      "key":"A",
      "price":"100"
   },
   {
      "_id":"555232",
      "name":"Something or another",
      "key":"B",
      "price":78
   }
]

2 个答案:

答案 0 :(得分:1)

这就是我做的事情

db.test.aggregate([
    {
        $group : {
            _id : '$key',
            maxVal : {$max : '$price'},
            others : {$push : '$$ROOT'}
        }
    },
    {
        $unwind : '$others'
    },
    {
        $project : {
            _id : '$others._id',
            name : '$others.name',
            key: '$others.key',
            price: '$others.price',
            pricecmp : {$cmp : ['$maxVal', '$others.price']}
        }
    },
    {
        $match : {pricecmp : {$eq : 0}}
    }
])

这将是输出

{
    "_id" : "555232",
    "name" : "Something or another",
    "key" : "B",
    "price" : 78,
    "pricecmp" : 0
}
{
    "_id" : "323232",
    "name" : "Something",
    "key" : "A",
    "price" : "100",
    "pricecmp" : 0
}

答案 1 :(得分:0)

我怀疑你可以使用一个阶段返回所有结果。就我的知识进行扩展而言,聚合会创建另一个带有结果的集合(如果我错了,希望其他人会纠正我)。您将获得最高价格和密钥,然后使用它来检索整个文档。

获取每个密钥的最高价格;这是你如何做到的:

db.collection.aggregate([{ $group:{ _id: "$key", maxprice:{$max:"$price"} } }])

<强>更新

评论中建议的link实际上使用$ sort和$ match,它也适用于你。

希望有所帮助

相关问题