MongoDB driver sort lookup results

I successfully completed the Get Comments lab of M220N. I used the Driver Linq technique. One of the instructions in the lab said that comments should be returned newest to oldest. I couldn’t find out how to sort the lookup results, so I ignored it and still passed the lab. Can anyone tell me how to sort the lookup results using Linq with the MongoDB driver.

Hi @Mike_Elvers, welcome to the community.
You can easily sort all the results in an aggregation pipeline by adding the $sort stage.

{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }

I hope it helps. Let me know if that answers your question or I am missing something here.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

Thanks, but that was not my question. I want to know how to sort Lookup results when using the Linq Lookup function with the MongoDB driver. Here is the current code:

await _moviesCollection.
Aggregate().
Match(Builders.Filter.Eq(x => x.Id, movieId)).
Lookup(_commentsCollection,
m => m.Id,
c => c.MovieId,
(Movie m) => m.Comments).
FirstOrDefaultAsync(cancellationToken);

What I want to do is only sort the results from the Lookup function?

Hi @Mike_Elvers, okay, hopefully, I got it this time.
If you want to sort the results produced by the lookup(in an array), you can use the alternate $lookup syntax as below:

{
   $lookup:
      {
         from: <joined collection>,
         let: { <var_1>: <expression>, …, <var_n>: <expression> },
         pipeline: [ <pipeline to run on joined collection> ],
         as: <output array field>
      }
}

you can specify the $sort stage in this lookup’s pipeline after joining both the collections using the right match conditions and hopefully you’ll get the desired output.

Please let us know how this goes.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

Are you saying there is no way to do this with Linq expressions?

Hi @Mike_Elvers, apologies for the delayed response.
Our soon-to-be-launched v2.14.0 of the dot-net driver comes with LINQ3.
LINQ3 can render LINQ join as $lookup, which you can use to achieve the same.
You can track our upcoming/past releases here: Driver Releases: Dot-Net

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

1 Like