Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 867
Patrick Meier Avatar asked Oct 21 '25 11:10

Patrick Meier


2 Answers

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!

like image 60
Patrick Meier Avatar answered Oct 23 '25 01:10

Patrick Meier


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!

like image 32
Patrick Meier Avatar answered Oct 23 '25 01:10

Patrick Meier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!