C#-How to specify an Order or Sort using the C# driver for MongoDB?

How to specify an Order or Sort using the C# driver for MongoDB?

I'm trying to figure out how to sort a collection of documents server side by telling the C# driver what the sort order is, but it appears not to support that construct yet.

Is it possible to do this any other way?

You can also do it using the SetSortOrder method on the MongoCursor class:

db["collection"].Find().SetSortOrder(SortBy.Ascending("SortByMe"));

Just to add to Chris's answer, in C# Driver 2.x it is now done with SortBySortByDescendingThenBy & ThenByDescending

collection.Find(bson => true).SortBy(bson => bson["SortByMeAscending"]).ThenByDescending(bson => bson["ThenByMeDescending"]).ToListAsync()

Now it resembles Linq even more.

For async methods:

var filter = Builders<BsonDocument>.Filter.Empty;
var sort = Builders<BsonDocument>.Sort.Ascending("time");
collection.FindAsync(filter, new FindOptions<BsonDocument, BsonDocument>()
{
    Sort = sort
});

Simple usage of api in MongoDB.Driver 2.5.0

var client = new MongoClient("mongodb://localhost:27017");

var database = client.GetDatabase("Blog");

var list = database.GetCollection<BlogPost>("BlogPost")
    .Find(e => e.Deleted == false)
    .SortByDescending(e => e.CreatedOn)
    .Limit(20)
    .ToList();

Note that to sort on multiple fields use this:

db["collection"].Find().SetSortOrder(SortBy.Ascending("SortByMe").Descending("An‌​dByMe");

If you want to use linq:

From the documentation: (http://docs.mongodb.org/ecosystem/tutorial/use-linq-queries-with-csharp-driver/)

var query=
    (from c in collection.AsQueryable<C>()
    orderby c.X
    select c)

foreach (var d in query)
{
    // process your documents
}

If you want you can also limit the results:

var query=
    (from c in collection.AsQueryable<C>()
    orderby c.X descending
    select c).Take(1);

Just remember to have an index on the field you are sorting by : ]

 

It seems the way to do this using the existing C# driver is as follows:

db["collection"].Find(new Document().Append("query", 
new Document()).Append("orderby", 
new Document().Append(name:1).Append(age,-1))); 

3,95355 gold badges3131 silver badges3636 bronze badges

  • 6

    See @Chris Brook's answer for a more C#-ish approach. – cdmckay Jul 30 '11 at 7:30

  • Personally a fan of the mongodb-ish approach – nik.shornikov Oct 30 '12 at 2:33

  • Changed the accepted answer to the newer style which wasn't available at the time the question was asked. – jmcd Apr 19 '13 at 22:13

@DmitryZyr's answer for FindAsync was not working. This one did however.

var sortDefinition = new SortDefinitionBuilder<ImmutableLog>().Descending("date");
var findOptions = new FindOptions<ImmutableLog>() {Sort = sortDefinition};
await this.Collection.FindAsync(new BsonDocument(), findOptions);

I'm doing this in JavaScript since I don't know C#, but it should have equivalent syntax with the C# driver.

If your query looked like:

db.c.find({"foo" : "bar"})

and you want to sort by "baz" ascending, wrap your query in a "query" field and add an "orderby" field:

db.c.find({"query" : {"foo" : "bar"}, "orderby" : {"baz" : 1}})

For descending sort, use -1.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值