signals4change
signals4change

Reputation: 53

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 keys, I can use

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

How do I sort with $natural?

Upvotes: 5

Views: 3576

Answers (2)

carmbrester
carmbrester

Reputation: 930

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

Upvotes: 2

Robert Stam
Robert Stam

Reputation: 12187

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

Upvotes: 8

Related Questions