2016-11-15 60 views
1

這是樣本數據(EXPIREDATE可選):在Reactivemongo Aggregation Framework中,如何在組函數「Max」中指定多個鍵?

{"userId":"1","appId":"1","createdDate":10} 
{"userId":"1","appId":"1","createdDate":5,"expireDate":30} 
{"userId":"1","appId":"1","createdDate":12,"expireDate":20} 
{"userId":"1","appId":"1","createdDate":12,"expireDate":5} 

這是我想翻譯到reactivemongo聚合框架的聚合功能:

db.collection_name.aggregate([ 
{ 
    $match : {"userId" : "1"} 
}, 
{ 
    $group : { 
     "_id" : "$appId", 
     "docs" : { 
      $max : { 
       "createdDate" : "$createdDate", 
       "expireDate" : "$expireDate" 
      } 
     } 
    } 
} 
]) 

在其上運行的樣本數據的聚合函數(蒙戈與外殼3.2.9),其結果是:

{ "_id" : "1", "docs" : { "createdDate" : 12, "expireDate" : 20 } } 

當我嘗試轉換此聚合函數reactivemong o,我意識到組函數「Max」只需要一個字符串作爲參數,所以我不知道如何將「createdDate」和「expireDate」都放在裏面。這是我到目前爲止的結果:

col.aggregate(
    Match(BSONDocument("userId" -> "1")), 
    List(Group(BSONString("$appId"))("docs" -> Max("createdDate"))) 
) 

有人可以告訴我如何將「expireDate」添加到「最大」功能?
請注意,我正在使用reactivemongo 0.11,並且升級到0.12不是一個選項。

回答

1

您可以使用reactivemongo.api.commands.AggregationFramework.GroupFunction.apply創建對組功能的自定義調用。 Here is the dochere is the source where I found it

GroupFunction("$max", BSONDocument("createdDate" -> "$createdDate", "expireDate" -> "$expireDate")) 

使用此功能,而不是Max,所以你的代碼變成:

col.aggregate(
    Match(BSONDocument("userId" -> "1")), 
    List(Group(BSONString("$appId"))("docs" -> GroupFunction("$max", BSONDocument("createdDate" -> "$createdDate", "expireDate" -> "$expireDate")))) 
) 

不要忘了導入col.BatchCommands.AggregationFramework.GroupFunction

當然,你可以定義一個更通用的功能,如果你想這需要任何BSONDocument作爲參數,:

def BetterMax(doc: BSONDocument) = GroupFunction("$max", doc) 
+0

感謝帕維爾,這個工程完美的我! –

相關問題