MongoDB - 按客户分组并以最高价格检索文档

时间:2013-03-10 11:00:54

标签: mongodb

考虑在db.invoices

中使用这些对象
{ "customer" : "john", "price" : 4, "weekday": "WED" }
{ "customer" : "john", "price" : 8, "weekday": "SUN" }
{ "customer" : "john", "price" : 6, "weekday": "SAT" }
{ "customer" : "john", "price" : 5, "weekday": "SUN" }    
{ "customer" : "bob", "price" : 10, "weekday": "SAT" }
{ "customer" : "bob", "price" : 15, "weekday": "MON" }

如何查询每位客户的最高价格的文件?以上样本:

[ {
  "customer": "bob",
  "price": 15,
  "weekday": "MON"
}, {
  "customer": "john",
  "price": 8,
  "weekday": "SUN"
} ]

我无法使用聚合框架来解决这个问题。

编辑1:问题是获得weekday以及客户名称。我不想单独的最高价格。

3 个答案:

答案 0 :(得分:3)

由于您希望包含weekday,因此您需要对文档进行预先排序,以便首先从每个组中提取所需的文档,然后将$group$first一起使用:

 
db.invoices.aggregate([
    {$sort: {customer: 1, price: -1}},
    {$group: {
        _id: '$customer',
        price: {$first: '$price'},
        weekday: {$first: '$weekday'}
    }}
])

答案 1 :(得分:1)

这是获得所需结果的方法,它是以下几种方法之一:

db.invoices.aggregate([
    {$project: {customer: 1, other:{ price: "$price", weekday: "$weekday"}}},
    {$group: {
        _id: '$customer',
        max: {$max: '$other'}
    }
])

答案 2 :(得分:0)

您可以使用$group运算符:

db.invoises.aggregate([
  { $group : { _id: '$customer', price: { $max: '$price' } } }
])