繁体   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