使用MongoDB和C#驱动程序计算排名

时间:2011-08-03 23:19:02

标签: asp.net-mvc-3 mongodb

我试图在MVC网站中使用MongoDB和C#驱动程序显示搜索排名以及结果。 我的目标是显示这样的网格:

  1. 这是结果
  2. 这是结果二
  3. 这是结果三
  4. 我的模特:

    public class Product
    {
        [BsonId]
        public string Id { get; set; }
    
        public string Name { get; set; }
    
        public int Rank { get; set; }
    }
    

    我从存储库层找到的代码如下所示:

        public IList<TEntity> Find<TEntity>(Expression<Func<TEntity, bool>> criteria) where TEntity : class
        {
            return this.GetQuery<TEntity>().AsQueryable().Where(criteria).ToList<TEntity>();
        }
    

    我的控制器看起来像这样:

        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);
        }
    

    Mongo.Find命令需要使用每条记录填充模型并计算排名(1,2,3等)。

    如何使用C#驱动程序解决此问题?我也在使用流利的linq提供商。

1 个答案:

答案 0 :(得分:1)

mongodb中没有Rank功能,因此驱动程序也不支持它。但我想这不是问题,因为您可以在加载数据时或在显示网格时在客户端建立行级别。

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;
}