Search code examples
c#.netmongodbmongodb-.net-driver

Sort by $natural in MongoDB with the official c# driver


I'm using the official C# driver and I want to sort a collection by $natural.

I know for sorting by keys, I can use

collection.Find(query).SetSortOrder(SortBy.Descending("Name"))

How do I sort with $natural?


Solution

  • Yes, you can use sort descending by it. For example:

    collection.Insert(new BsonDocument("x", 1));
    collection.Insert(new BsonDocument("x", 2));
    collection.Insert(new BsonDocument("x", 3));
    
    foreach (var document in collection.FindAll()
        .SetSortOrder(SortBy.Descending("$natural"))) 
    {
        Console.WriteLine(document.ToJson());
    }