How to specify an Order or Sort using the C# driver for MongoDB?

I'm trying to figure out how to sort a collection of documents server side by telling the C# driver what the sort order is, but it appears not to support that construct yet.

Is it possible to do this any other way?


Solution 1:

You can also do it using the SetSortOrder method on the MongoCursor class:

db["collection"].Find().SetSortOrder(SortBy.Ascending("SortByMe"));

Solution 2:

Just to add to Chris's answer, in C# Driver 2.x it is now done with SortBy, SortByDescending, ThenBy & ThenByDescending

collection.Find(bson => true).SortBy(bson => bson["SortByMeAscending"]).ThenByDescending(bson => bson["ThenByMeDescending"]).ToListAsync()

Now it resembles Linq even more.

http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/crud/reading/#sort

Solution 3:

For async methods:

var filter = Builders<BsonDocument>.Filter.Empty;
var sort = Builders<BsonDocument>.Sort.Ascending("time");
collection.FindAsync(filter, new FindOptions<BsonDocument, BsonDocument>()
{
    Sort = sort
});