如何使用 MongoDB 的 C# 驱动程序指定顺序或排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2123529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:41:59  来源:igfitidea点击:

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

c#mongodbsorting

提问by jmcd

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.

我试图通过告诉 C# 驱动程序排序顺序来弄清楚如何对文档服务器端的集合进行排序,但它似乎还不支持该构造。

Is it possible to do this any other way?

有没有可能以其他方式做到这一点?

采纳答案by Chris Brook

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

您还可以使用 MongoCursor 类上的 SetSortOrder 方法来完成此操作:

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

回答by kristina

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

我在 JavaScript 中这样做,因为我不知道 C#,但它应该具有与 C# 驱动程序等效的语法。

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:

并且您想按“baz”升序排序,将您的查询包装在“查询”字段中并添加一个“orderby”字段:

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

For descending sort, use -1.

对于降序排序,请使用 -1。

回答by jmcd

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

使用现有的 C# 驱动程序执行此操作的方法如下:

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

Which I was turned on to by Sam Corder here

我在这里被 Sam Corder 打开

回答by Darius

Note that to sort on multiple fields use this:

请注意,要对多个字段进行排序,请使用以下命令:

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

回答by Shy Peleg

If you want to use linq:

如果你想使用 linq:

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

从文档:(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 : ]

请记住在您排序的字段上有一个索引:]

回答by Sergej Popov

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

只是为了添加到 Chris 的答案,在 C# Driver 2.x 中,它现在使用SortBy, SortByDescending, ThenBy&ThenByDescending

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

Now it resembles Linq even more.

现在它更像 Linq。

http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/crud/reading/#sort

http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/crud/reading/#sort

回答by DmitryZyr

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

回答by Mohammad Akbari

Simple usage of api in MongoDB.Driver 2.5.0

MongoDB.Driver 2.5.0中api的简单使用

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

回答by Hyman

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

@DmitryZyr 对 FindAsync 的回答不起作用。然而,这一点做到了。

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