2011-06-22 37 views
5

我使用官方的C#驅動程序,並且我想按$natural對收集進行排序。

我知道通過鍵排序,我可以用

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

我怎麼樣跟$natural

+0

重要提示:有沒有必要由升$自然順序進行排序。這是MongoDB自然返回結果的順序。 – i3arnon

回答

8

是的,你可以使用降序排序。例如:

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()); 
} 
+0

非常感謝 – signals4change

0

更新羅伯特·斯塔姆的答案的東西大致相當,使用語法爲2.0驅動程序...

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()); 
} 
相關問題