使用project和$ map的Spring Data MongoDB Aggregation

时间:2017-05-12 19:43:38

标签: spring mongodb spring-mongodb

我想知道以下本机mongoDB查询的SpringData等效代码。

{
    $project: {
        _id: "$_id",
        login: "$login",
        firstName: "$firstName",
        lastName: "$lastName",
        email: "$email",
        deactivateFlag: "$deactivateFlag",
        createdOn: "$createdOn",
        createdBy: {
            "$map": {
                "input": "$created_by",
                "as": "u",
                "in": {
                    "name": {
                        "$concat": ["$$u.firstName", " ", "$$u.lastName"]
                    },
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是一个老问题,但如果其他人在谷歌搜索中找到它,这就是如何解决它。实际上,您可以为Spring JPA无法开箱即用的任何复杂的mongodb查询执行此操作。

您需要编写自定义文档以注入投影。这个例子在Kotlin中,但你会得到Java的想法。我没有正确测试它,但应该得到你想要的东西。

val mapExpression = BasicDBObject()

mapExpression["input"] = "\$created_by"
mapExpression["as"] = "u"

val concat = BasicDBObject("\$concat", listOf("\$\$u.firstName", " ", "\$\$u.lastName"))

mapExpression["in"] = BasicDBObject("name", concat)

val createdByFilter =  Document("\$map", mapExpression)

project("_id", "login", "firstName", "lastName", "email", "deactivateFlag", "createdOn").and(createdByFilter).`as`("createdBy")