簡體   English   中英

使用官方c#驅動程序在MongoDB中按$ natural排序

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

我正在使用官方的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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM