2013-03-10 58 views
2

考慮db.invoicesMongoDB的 - 組:客戶和檢索與最高價格文件

{ "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

因爲要包括weekday你需要預先排序的文檔,首先把你從每個組想要的文檔,然後使用$group$first

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

謝謝!是否有一種方法可以包括除命名每個組的操作之外的所有其他字段? – 2013-03-10 18:47:59

+0

不是我所知道的,沒有。 – JohnnyHK 2013-03-10 18:49:41

+0

有,但只有當你知道你想包括的字段的名稱 - 一般沒有辦法包括「其餘的字段」。 – 2013-03-10 20:37:23

0

您可以使用$group操作:

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

這不會給'weekday's給我!這就是問題 – 2013-03-10 18:17:42

+0

我的粗心:) – user20140268 2013-03-10 19:50:33

1

這裏有一種方式來獲得你想要的結果,這是其中的一個例子:

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