GetComment and sorting problem

Hi. I don’t know how to sort comments by date inside the result document. Below code is not working:

List<Bson> pipeline = new ArrayList<>();

// match stage to find movie

Bson match = Aggregates.match(Filters.eq("_id", new ObjectId(movieId)));

// TODO> Ticket: Get Comments - implement the lookup stage that allows the comments to

Bson lookUp = Aggregates.lookup("comments","_id","movie_id","comments");
Bson sort = Aggregates.sort(Sorts.descending(""));

testGetMovieComments in GetCommentsTest class still failing.
org.junit.ComparisonFailure: Expected name field does match: check your getMovie() comments sort order.
Expected :Arya Stark
Actual :Grey Worm

Where I’m making mistake?

Hi @Michal_56787,


Hmm… I implemented a weird way that works for me. Hope works for you, too :o)
The long story short is: match movie, lookup movie with comments, unwind the array comments, sort comments, group on _id (and other attributes) to recreate the comments array, by using push.
Please let me know if you have a better way.

    Bson match = match(Filters.eq("_id", new ObjectId(movieId)));
    Bson lookup = lookup("comments", "_id", "movie_id", "comments" );
    Bson unwind = unwind("$comments");
    Bson sort = sort(Sorts.descending("" ));
    Bson group = group("$_id"
            // I commented out the original movie's columns 
            , Accumulators.first("fullplot", "$fullplot")
            , Accumulators.first("imdb", "$imdb")
            , Accumulators.first("year", "$year")
            , Accumulators.first("plot", "$plot")
            , Accumulators.first("genres", "$genres")
            , Accumulators.first("rated", "$rated")
            , Accumulators.first("metacritic", "$metacritic")
            , Accumulators.first("title", "$title")
            , Accumulators.first("lastupdated", "$lastupdated")
            , Accumulators.first("languages", "$languages")
            , Accumulators.first("writers", "$writers")
            , Accumulators.first("type", "$type")
            , Accumulators.first("tomatoes", "$tomatoes")
            , Accumulators.first("poster", "$poster")
            , Accumulators.first("num_mflix_comments", "$num_mflix_comments")
            , Accumulators.first("released", "$released")
            , Accumulators.first("awards", "$awards")
            , Accumulators.first("countries", "$countries")
            , Accumulators.first("cast", "$cast")
            , Accumulators.first("directors", "$directors")
            , Accumulators.first("runtime", "$runtime")
            , Accumulators.push("comments", "$comments") );

match, lookup can be prefixed by Aggregates.

1 Like