Spring Data MongoDB:聚合框架 - 使用嵌套属性排序会引发无效引用

时间:2014-03-10 11:55:59

标签: java spring mongodb spring-data spring-data-mongodb

我发现this article in Spring Forum显然在一定程度上讨论了同样的问题,但对我的问题没有答案。

鉴于以下文件......

{
    "_id": { "$oid": "5214b5d529ee12460939e2ba"},
    "title": "this is my title",
    "tags": [ "fun", "sport" ],
    "comments": [
        {
            "author": "alex",
            "text": "this is cool",
            "createdAt": 1
        },
        {
            "author": "sam",
            "text": "this is bad",
            "createdAt": 2
        },
        {
            "author": "jenny",
            "text": "this is bad",
            "createdAt": 3
        }
    ]
}

...我想做这个聚合(Javascript)......

//This is as concise as possible to focus on the actual problem which is the sort operation when ported to Spring!  
db.articles.aggregate( 
    {$unwind:"$comments"},
    //do more like match, group, etc...
    {$sort:{"comments.createdAt":-1}} //Sort descending -> here the problem occurs in Spring (works in Javascript!)
);

...但是有了Spring - >引发无效的参考!

Aggregation agg = newAggregation(
       unwind("comments"),
       sort(Direction.DESC, "comments.createdAt") //Throws invalid reference 'comments.createdAt'!
       //How can I make this work? 
);

当然我可以使用本机Java驱动程序并且不使用Spring的MongoTemplate,但我不太喜欢这种方法。我该怎么做才能使这个精确的聚合与Spring一起工作?

我使用的是当前版本1.4.0.RELEASE。

1 个答案:

答案 0 :(得分:2)

发布的代码确实成功 - 我遇到的问题是其他问题。

我做了类似的事情:

Aggregation agg = newAggregation(
       project("comments"), //This was the problem! Without this it works as desired!
       unwind("comments"),
       sort(Direction.DESC, "comments.createdAt") 
);

正如我在代码中写的那样,我只想投影 comments -Field以节省一些开销 - 但这实际上导致了我的问题!

非常感谢提示!