开发者

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.

I know for sorting by k开发者_如何学编程eys, I can use

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

How do I sort with $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...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜