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?
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?
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();
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)));
Which I was turned on to by Sam Corder here
You can apply sort with SortDefinition like this:
FilterDefinition<User> filter = Builders<User>.Filter.Eq(a => a.Deleted , false);
SortDefinition<User> sort = Builders<User>.Sort.Descending(a => a.Id);
List<User> result = _dbContext.Users.Find(filter).Sort(sort).Limit(10).ToList();
@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 currently using the API version MongoDB.Driver 2.8.1. Here is my method that I call to return a list of objects with Descending sorting, if it is required:
public static IEnumerable<TEntity> GetDocumentsForCollection(
IMongoDatabase database,
string collectionName,
FilterDefinition<TEntity> query,
string databaseCollectionKeyToSortOnDescending)
{
var _mongoSettings = new MongoCollectionSettings();
_mongoSettings.GuidRepresentation = GuidRepresentation.Standard;
var _collection = database.GetCollection<TEntity>(collectionName, _mongoSettings);
if (string.IsNullOrEmpty(databaseCollectionKeyToSortOnDescending))
{
return _collection.Find(query).ToList();
}
return _collection.Find<TEntity>(query).Sort(Builders<TEntity>.Sort.Descending(databaseCollectionKeyToSortOnDescending)).ToList();
}
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.