Spring Data MongoDB: aggregation framework - sort with nested property throws invalid reference

人走茶凉 提交于 2019-12-11 02:08:22

问题


I found this article in Spring Forum which obviously dicusses partly the same problem, but has no answer to my question.

Given the following document...

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

... I want to do this aggregation (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!)
);

... but with Spring -> Throws Invalid Reference!

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

Of course I can do it with the native Java-Driver and without usage of Spring's MongoTemplate but I don't like this approach very much. What can I do to make this exact aggregation work with Spring?

I am using the current Version 1.4.0.RELEASE.


回答1:


The code as posted indeed works successfully - the problem I had was something else.

I did something like this:

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

As I wrote in the code I wanted to project only the comments-Field to save some overhead - but this acutally caused my problem!

Thanks a lot for the hint!



来源:https://stackoverflow.com/questions/22299411/spring-data-mongodb-aggregation-framework-sort-with-nested-property-throws-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!