1

这是示例数据(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}

这是我想翻译成reactivemongo聚合框架的聚合函数:

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

对样本数据运行聚合函数(使用 mongo shell 3.2.9),结果为:

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

当我尝试将此聚合函数转换为reactivemongo时,我意识到组函数“Max”只接受一个字符串作为参数,所以我不知道如何将“createdDate”和“expireDate”都放入其中。到目前为止,这是我发现的:

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

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

4

1 回答 1

1

您可以使用reactivemongo.api.commands.AggregationFramework.GroupFunction.apply创建对组函数的自定义调用。这是文档这里是我找到它的来源

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,如果需要,您可以定义一个更通用的函数,该函数将 any 作为参数:

def BetterMax(doc: BSONDocument) = GroupFunction("$max", doc)
于 2016-11-18T13:51:44.143 回答