4

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
  • 1
    Works for me. Can you please show Post and Comment mapping? Commented Mar 10, 2014 at 13:17

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.