使用官方c#驱动程序在MongoDB中按$ natural排序

|| 我正在使用官方的C#驱动程序,我想按
$natural
对集合进行排序。 我知道要按键排序,我可以使用
collection.Find(query).SetSortOrder(SortBy.Descending(\"Name\"))
如何用
$natural
排序?     
已邀请:
        是的,您可以使用降序排列。例如:
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());
}
    
        使用2.0驱动程序的语法将Robert Stam的答案更新为大致等效的内容...
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());
}
    

要回复问题请先登录注册