Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 311
signals4change Avatar asked Jun 22 '11 04:06

signals4change


People also ask

What is the use of sort () in MongoDB?

This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field.

Which sorting is supported by MongoDB?

MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted. The sort keys must be listed in the same order as defined in the index.

What is the default sort order in MongoDB?

by default mongo appears to return documents in insertion order. MongoDB returns documents in natural order when no sort order is specified.


2 Answers

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());
}
like image 171
Robert Stam Avatar answered Oct 13 '22 11:10

Robert Stam


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());
}
like image 36
carmbrester Avatar answered Oct 13 '22 12:10

carmbrester