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
?
This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field.
MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted. The sort keys must be listed in the same order as defined in the index.
by default mongo appears to return documents in insertion order. MongoDB returns documents in natural order when no sort order is specified.
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());
}
Updated Robert Stam's answer to something roughly equivalent, using the syntax for the 2.0 driver...
await collection.InsertOneAsync(new BsonDocument("x", 1));
await collection.InsertOneAsync(new BsonDocument("x", 2));
await collection.InsertOneAsync(new BsonDocument("x", 3));
foreach (
var document in
await
collection.Find(_ => true)
.Sort(new SortDefinitionBuilder<BsonDocument>().Descending("$natural"))
.ToListAsync())
{
Console.WriteLine(document.ToJson());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With