简体   繁体   English

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

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

I'm using the official C# driver and I want to sort a collection by $natural . 我正在使用官方的C#驱动程序,我想用$natural对系列进行排序。

I know for sorting by keys, I can use 我知道按键排序,我可以使用

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

How do I sort with $natural ? 我如何用$natural排序?

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... 使用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