Calculating rank with MongoDB and C# driver
I am trying to display a search rank along with the results using MongoDB and the C# driver in an MVC website. My goal is to display a grid something like this:
- This is result one
- This is result two
- This is result three
My model:
public class Product
{
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
public int Rank { get; set; }
}
My find code from the repository layer looks like this:
public IList<TEntity> Find<TEntity>(Expression<Func<TEntity, bool>> criteria) where TEntity : class
{
return this.GetQuery<TEntity>().AsQueryable().Where(criteria).ToList<TEntity>();
}
My controller looks like this:
public ActionResult Index(string query)
{
var model = new SearchModel();
model.Results = this.Repository.Find<Product>(x => x.Name == “some query”)
.OrderBy(model.GridSortOptions.Column, model.GridSortOptions.Direction)
.AsPagination(1, 25);
return View(model);开发者_运维技巧
}
The Mongo.Find command needs to populate the model with the each record and calculate the rank (1, 2, 3 etc.).
How do I go about this using the C# driver? I am also using the fluent linq provider.
There is no Rank function in mongodb therefore driver not support it as well. But i guess it not a problem because you can build row rank on the client side when you've loaded data or when you will display a grid.
var pagingSkip = 1;
model.Results = this.Repository.Find<Product>(x => x.Name == “some query”)
.OrderBy(model.GridSortOptions.Column, model.GridSortOptions.Direction)
.AsPagination(pagingStart, 25);
foreach(var item in model.Results)
{
item.Rank = pagingSkip + 1;
}
精彩评论