How to specify an Order or Sort using the C# driver for MongoDB?
You can also do it using the SetSortOrder method on the MongoCursor class:
db["collection"].Find().SetSortOrder(SortBy.Ascending("SortByMe"));
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
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
});