2

考虑将这些对象放入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与客户姓名一起使用。我不想要单独的最高价格。

4

3 回答 3

3

因为要包含,所以weekday需要对文档进行预排序,以首先从每个组中放入所需的文档,然后使用$groupwith $first

db.invoices.aggregate([
    {$sort: {customer: 1, price: -1}},
    {$group: {
        _id: '$customer',
        price: {$first: '$price'},
        weekday: {$first: '$weekday'}
    }}
])
于 2013-03-10T18:36:27.097 回答
1

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

db.invoices.aggregate([
    {$project: {customer: 1, other:{ price: "$price", weekday: "$weekday"}}},
    {$group: {
        _id: '$customer',
        max: {$max: '$other'}
    }
])
于 2013-03-10T20:46:26.543 回答
0

您可以使用$group运算符:

db.invoises.aggregate([
  { $group : { _id: '$customer', price: { $max: '$price' } } }
])
于 2013-03-10T13:15:47.570 回答