在Reactivemongo Aggregation Framework中,如何在组函数"Max"中指定多个键?

In Reactivemongo Aggregation Framework, how to specify multiple keys in the group function "Max"?

这是示例数据(expireDate 是可选的):

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

这是我要转换为响应式mongo聚合框架的聚合函数:

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

对样本数据进行运行聚合函数(用mongoshell3.2.9),结果为:

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

当我尝试将此聚合函数转换为反应式mongo时,我意识到组函数"Max"只接受一个字符串作为参数,所以我不知道如何将两个"createdDate" 和 "expireDate" 在其中。到目前为止,这是我弄清楚的:

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

谁能告诉我如何将 "expireDate" 添加到 "Max" 函数中?
请注意,我使用的是 reactivemongo 0.11,升级到 0.12 不是一个选项。

您可以使用 reactivemongo.api.commands.AggregationFramework.GroupFunction.apply 创建对组函数的自定义调用。 Here is the doc and here 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)