考虑将这些对象放在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和客户名称时出现问题。我不想要单独的最高价格。
发布于 2013-03-11 02:36:27
因为您希望包含weekday,所以需要对文档进行预排序,以便首先从每个组中放置所需的文档,然后将$group与$first一起使用
db.invoices.aggregate([
{$sort: {customer: 1, price: -1}},
{$group: {
_id: '$customer',
price: {$first: '$price'},
weekday: {$first: '$weekday'}
}}
])发布于 2013-03-11 04:46:27
这里有一种方法可以得到你想要的结果,它是几种方法之一:
db.invoices.aggregate([
{$project: {customer: 1, other:{ price: "$price", weekday: "$weekday"}}},
{$group: {
_id: '$customer',
max: {$max: '$other'}
}
])发布于 2013-03-10 21:15:48
您可以使用$group运算符:
db.invoises.aggregate([
{ $group : { _id: '$customer', price: { $max: '$price' } } }
])https://stackoverflow.com/questions/15321485
复制相似问题