Reputation: 669
I am trying to retrieve five recent documents from "Deal" collection in a MongoDB using C# driver for MongoDB. I can do it with the below code.
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 recent 5 documents and FindAll() loads all the documents in the collection. I tried to do it with Find() but it needs a query as a parameter. How can I write a query for "orderby" in Mongo driver for C# to sort?
https://stackoverflow.com/a/2148479/778101 asked a similar question here. But the accepted answer doesn't work for me.
Upvotes: 9
Views: 19153
Reputation: 669
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);
}
}
is also a correct method to solve this problem
Upvotes: 11
Reputation: 12646
Looks like the accepted answer is out of date or I don't understand it. This is how you order by in MongoDb C# Driver 2.0:
var list = await collection
.Find(fooFilter)
.Sort(Builders<BsonDocument>.Sort.Descending("NameOfFieldToSortBy")
.ToListAsync();
Upvotes: 6
Reputation: 12187
FindAll is just a shortcut for Find(Query.Null).
There is no reason you can't use SetSortOrder and SetLimit with FindAll.
Upvotes: 0
Reputation: 3020
You can use MongoDB.Driver.Builders.Query.Null
as IMongoQuery parameter for Find() and than do the SetSortOrder().SetLimit()
Your code can be like
dbContext.Set() .Find(Query.Null).SetSortOrder(SortBy.Descending("ModifiedDateTime")) .SetLimit(5);
Upvotes: 1
Reputation: 53685
You should use Find method. Query.And()
in c# will be equivalent to empty query {}
at mongodb shell. So full example will looks like:
dbContext.Set<TEntity>()
.Find(Query.And())
.SetSortOrder(SortBy.Descending("ModifiedDateTime"))
.SetLimit(5);
Actually if you collection strong typed it have method Find(IMongoQuery query)
, if not then it have method FindAs<Type>(IMongoQuery query)
.
Upvotes: 0