2016-08-12 121 views
1

進行放鬆,我aggreagate管道我有中間結果如後:MongoDB的與特定領域的最大價值每組查找文件(argmax)

[ 
{_id:1, precision:0.91, recall:0.71, other fields...}, 
{_id:1, precision:0.71, recall:0.81, other fields...}, 
{_id:1, precision:0.61, recall:0.91, other fields...}, 
{_id:2, precision:0.82, recall:0.42, other fields...}, 
{_id:2, precision:0.72, recall:0.52, other fields...}, 
{_id:2, precision:0.62, recall:0.62, other fields...} 
] 

現在我想組文件由_id,然後在每個組中查找具有最大召回的文件,並獲得該文件的召回,精確度和_id。

那麼結果將是:

[ 
    {_id:1, precisionOfDocWithMaxRecall:0.61, maxRecall:0.91}, 
    {_id:2, precisionOfDocWithMaxRecall:0.62, maxRecall:0.62} 
] 

我已成功地獲得使用羣體和最大,但沒有精確場的結果。

回答

2

您可以運行下面的管道,它採用了$sort運營商訂購漸入$group管道第一的文件,然後使用$first(或$last,根據排序方向)返回有序列表中的第一個/最後一個元素:

db.collection.aggregate([ 
    /* previous pipeline */ 
    { "$sort": { "recall": -1 } }, 
    { 
     "$group": { 
      "_id": "$_id", 
      "precisionOfDocWithMaxRecall": { "$first": "$precision" }, 
      "maxRecall": { "$first": "$recall" } 
     } 
    } 
])