2011-06-22 30 views
5

Tôi đang sử dụng trình điều khiển C# chính thức và tôi muốn sắp xếp bộ sưu tập theo $natural.

tôi biết sắp xếp theo chìa khóa, tôi có thể sử dụng

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

Làm thế nào để loại với $natural?

+0

Lưu ý quan trọng: Không cần để sắp xếp theo ascending $ trật tự tự nhiên. Đó là thứ tự MongoDB 'tự nhiên' trả về kết quả. – i3arnon

Trả lời

8

Có, bạn có thể sử dụng sắp xếp giảm dần. Ví dụ:

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

cảm ơn bạn rất nhiều – signals4change

0

Cập nhật Robert Stam của câu trả lời cho một cái gì đó tương đương, sử dụng cú pháp cho người lái xe 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()); 
} 
Các vấn đề liên quan