How to write a query for "orderby" in Mongo driver for C # for sorting?

I am trying to extract the last five documents from the Deal collection in MongoDB using the C # driver for MongoDB. I can do this using the code below.

public IList<TEntity> GetRecentFive() { IList<TEntity> entities = new List<TEntity>(); using (MongoDbContext dbContext = new MongoDbContext(_dbFactory)) { var cursor = dbContext.Set<TEntity>().FindAll().SetSortOrder(SortBy.Descending("ModifiedDateTime")).SetLimit(5); foreach (TEntity entity in cursor) { entities.Add(entity); } } return entities; } 

But I want to get only the last 5 documents, and FindAll () loads all the documents in the collection. I tried to do this with Find (), but for this I need a query as a parameter. How can I write a query for "orderby" in the Mongo driver to sort C #?

stack overflow.squite But the accepted answer does not work for me.

+8
c # mongodb mongodb-.net-driver
source share
5 answers
 using (MongoDbContext dbContext = new MongoDbContext(_dbFactory)) { var query = new QueryDocument(); var cursor = dbContext.Set<TEntity>().Find(query).SetSortOrder(SortBy.Descending("ModifiedDateTime")).SetLimit(5); foreach (TEntity entity in cursor) { entities.Add(entity); } } 

It is also the correct method to solve this problem.

+10
source share

It seems that the accepted answer is out of date or I do not understand it. So you order in MongoDb C # Driver 2.0:

 var list = await collection .Find(fooFilter) .Sort(Builders<BsonDocument>.Sort.Descending("NameOfFieldToSortBy") .ToListAsync(); 
+2
source share

You can use MongoDB.Driver.Builders.Query.Null as the IMongoQuery parameter for Find () rather than SetSortOrder().SetLimit()

Your code may be like

 dbContext.Set ()
          .Find (Query.Null) .SetSortOrder (SortBy.Descending ("ModifiedDateTime"))
          .SetLimit (5);
+1
source share

You must use the search method. Query.And() in C # will be equivalent to an empty query {} in the mongodb shell. Thus, a complete example would look like this:

 dbContext.Set<TEntity>() .Find(Query.And()) .SetSortOrder(SortBy.Descending("ModifiedDateTime")) .SetLimit(5); 

Actually, if you entered a strong string, it has a Find(IMongoQuery query) method, if not, it has a FindAs<Type>(IMongoQuery query) method.

0
source share

FindAll is just a shortcut to Find (Query.Null).

There is no reason why you cannot use SetSortOrder and SetLimit with FindAll.

0
source share

All Articles