考虑在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
以及客户名称。我不想单独的最高价格。
答案 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' } } }
])