Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Is there a sorting function in C?

Standard C library provides qsort function that can be used for sorting an array.

What is selection sort in C with example?

Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.

How do you write ascending order in C?

Just use > (greater than) instead of < (less than) in logic. Note: In above C program, fixed numbers are used to sort in ascending order.


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
});

Simple usage of api in MongoDB.Driver 2.5.0

var client = new MongoClient("mongodb://localhost:27017");

var database = client.GetDatabase("Blog");

var list = database.GetCollection<BlogPost>("BlogPost")
    .Find(e => e.Deleted == false)
    .SortByDescending(e => e.CreatedOn)
    .Limit(20)
    .ToList();

Note that to sort on multiple fields use this:

db["collection"].Find().SetSortOrder(SortBy.Ascending("SortByMe").Descending("An‌​dByMe");

If you want to use linq:

From the documentation: (http://docs.mongodb.org/ecosystem/tutorial/use-linq-queries-with-csharp-driver/)

var query=
    (from c in collection.AsQueryable<C>()
    orderby c.X
    select c)

foreach (var d in query)
{
    // process your documents
}

If you want you can also limit the results:

var query=
    (from c in collection.AsQueryable<C>()
    orderby c.X descending
    select c).Take(1);

Just remember to have an index on the field you are sorting by : ]