Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 396
har Avatar asked Feb 17 '12 09:02

har


2 Answers

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();
like image 179
VSO Avatar answered Sep 21 '22 15:09

VSO


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

like image 38
har Avatar answered Sep 22 '22 15:09

har