Mongodb for C# 分组查询

#region 排序获取集合 static List<BsonDocument> GetPagerWithGroup(string connectionString, string databaseName,      string collectionName, IMongoQuery param, GroupByBuilder groupByBuilder, PageInfo info, out int pageCount)
        /// <summary>
        ///分组查询获取集合
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="databaseName">数据库名称</param>
        /// <param name="collectionName">集合名称</param>
        /// <param name="param">条件</param>
        /// <param name="groupByBuilder">分组条件</param>
        /// <param name="info">分页信息</param>
        /// <param name="pageCount">总页数</param>
        /// <returns>List</returns>
        public static List<BsonDocument> GetPagerWithGroup(string connectionString, string databaseName,
            string collectionName, IMongoQuery param, GroupByBuilder groupByBuilder, PageInfo info, out int pageCount)
        {

            var collection = GetMongoCollection<BsonDocument>(connectionString, databaseName, collectionName);
            var dictionary = new Dictionary<string, int>();
            dictionary["num"] = 0;
            List<BsonDocument> list = null;
            var q = collection.Group(param, groupByBuilder, BsonDocument.Create(dictionary),
                BsonJavaScript.Create("function(doc,prev){prev.num++;}"),
                BsonJavaScript.Create("function(doc){ doc.count=doc.num;delete doc.num; }"));
        
            pageCount = 0;
            if (info == null)
            {
                list = q.ToList();
            }
            else
            {
                list = q
            .Skip((info.PageIndex - 1) * info.PageSize).Take(info.PageSize).ToList();
                var count = q.Count();
                if (count <= 0)
                {
                    pageCount = 0;
                    return null;
                }
                pageCount = (int)(count % info.PageSize == 0 ? count / info.PageSize : (count / info.PageSize) + 1);
            }

            return list;
        }
        #endregion

 

posted @ 2015-02-06 14:20  b̶i̶n̶g̶.̶  阅读(580)  评论(1编辑  收藏  举报