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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...