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

本文关键字:中按 MongoDB natural 排序 驱动程序 官方 | 更新日期: 2023-09-27 18:00:02

我使用的是官方的C#驱动程序,我想按$natural对集合进行排序。

我知道按键排序,我可以使用

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

如何使用$natural进行排序?

使用官方的c#驱动程序在MongoDB中按$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());
}