1. 程式人生 > >MongoDB 的分組操作 In C#

MongoDB 的分組操作 In C#

C#對mongodb的分組查詢操作,主要通過指令碼或Aggregate方法來實現,以下通過一些例項作解析:

參考資料:http://www.tuicool.com/articles/2iqUZj

       http://www.cnblogs.com/vnii/archive/2012/08/23/2652891.html

       http://www.cnblogs.com/zhwl/archive/2013/12/19/3482140.html

1. 根據任務id進行分組,統計每個任務的瀏覽數量。

複製程式碼
        public static List<vm_quantityModel> GetMyIncomeDetail(int
member_id, int pageIndex, int pageSize, out int totalCount) { //篩選條件 IMongoQuery query = Query.And(Query.EQ("member_id", member_id), Query.EQ("mark", 1)); MongoCollection<BsonDocument> myCollection = MongoDBHelper.GetCollection("mstg_record_history
"); //分組 Dictionary<string, int> dic_initial = new Dictionary<string, int>(); dic_initial["num"] = 0; var r = myCollection.Group( query, "task_id", //分組的欄位 BsonDocument.Create(dic_initial), BsonJavaScript.Create(
"function(doc,prev){prev.num++;}"), null ).ToList(); List<vm_quantityModel> result = new List<vm_quantityModel>(); if (r != null && r.Count > 0) { foreach (var item in r) { vm_quantityModel m = new vm_quantityModel(); m.task_id = Common.StringHelper.StrToInt(item["task_id"].ToString()); m.valid_count = Common.StringHelper.StrToLong(item["num"].ToString()); result.Add(m); } } totalCount = result.Count; result = result.OrderByDescending(x => x.task_id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); return result; }
複製程式碼

2.根據會員編號分組,累加價格的統計

複製程式碼
        /// <summary>
        /// 幫幫賺會員總收益
        /// </summary>
        /// <param name="memberIds"></param>
        /// <returns></returns>
        public static List<vm_rankingModel> GetBangZhuanList(List<int> memberIds)
        {
            var ids = memberIds.ConvertAll<BsonValue>(x => x);
            //篩選欄位
            IMongoQuery query = Query.And(Query.In("member_id", ids), Query.EQ("mark", 1));

            MongoCollection<BsonDocument> myCollection = MongoDBHelper.GetCollection("mstg_record_history");

            //GroupBy的欄位
            GroupByBuilder groupbyBuilder = new GroupByBuilder(new string[] { "member_id" });

            Dictionary<string, double> dic_M = new Dictionary<string, double>();
            dic_M["msum"] = 0.0;
            var result_M = myCollection.Group(query, groupbyBuilder, BsonDocument.Create(dic_M),
                                            BsonJavaScript.Create("function(obj,prev){prev.msum += obj.price;}"),
                                            BsonJavaScript.Create("function(obj){obj.sum=obj.msum;delete obj.sum;}")).ToList();

            List<vm_rankingModel> result = new List<vm_rankingModel>();
            if (result_M != null && result_M.Count > 0)
            {
                foreach (var item in result_M)
                {
                    double amount = Math.Round(Convert.ToDouble(item["msum"]), 2);
                    result.Add(new vm_rankingModel
                    {
                        member_id = Common.StringHelper.StrToInt(item["member_id"].ToString()),
                        amount = amount
                    });
                }
            }            

            result = result.OrderByDescending(x => x.amount).ToList();

            return result;            
        }
複製程式碼

用Aggregate實現:

複製程式碼
        public static List<vm_rankingModel> GetRankingList(int top)
        {
            MongoCollection<BsonDocument> myCollection = MongoDBHelper.GetCollection("mstg_record_history");

            //分組獲取金額總數
            var group = new BsonDocument 
                { 

                    { "$group", 
                        new BsonDocument 
                            { 
                                { "_id", new BsonDocument 
                                             { 
                                                 { 
                                                     "MemberId","$member_id" 
                                                 } 
                                             } 
                                }, 
                                { 
                                    "Count", new BsonDocument 
                                                 { 
                                                     { 
                                                         "$sum", "$price" 
                                                     } 
                                                 } 
                                } 
                            } 
                  } 
                };
            //篩選條件
            var match = new BsonDocument 
                { 
                    { 
                        "$match", 
                        new BsonDocument 
                            { 
                                {"mark", 1}
                            } 
                    } 
                };

            var pipeline = new[] { match, group };
            var list = myCollection.Aggregate(pipeline);

            var matchingExamples = list.ResultDocuments
            .Select(x => x.ToDynamic())
            .ToList();
            List<vm_rankingModel> result = new List<vm_rankingModel>();

            //foreach (var example in matchingExamples)
            //{
            //    var message = string.Format("{0} - {1}", example._id.MyUser, example.Count);
            //    Console.WriteLine(message);
            //}

            if (matchingExamples.Count > 0)
            {
                foreach (var example in matchingExamples)
                {
                    int member_id = Convert.ToInt32(example._id.MemberId.Value);
                    double amount = Math.Round(example.Count.Value, 2);
                    result.Add(new vm_rankingModel
                    {
                        member_id = member_id,
                        amount = amount
                    });
                }
            }
            
            result = result.OrderByDescending(x => x.amount).Take(top).ToList();

            return result;
        }
複製程式碼

3. 按日期分組,累加價格的統計

複製程式碼
        public static List<vm_bangzhuan_detailModel> GetBangZhuanDetails(List<int> memberIds)
        {
            var ids = memberIds.ConvertAll<BsonValue>(x => x);
            //有效瀏覽數
            IMongoQuery query = Query.And(Query.In("member_id", ids), Query.EQ("mark", 1));

            MongoCollection<BsonDocument> myCollection = MongoDBHelper.GetCollection("mstg_record_history");          

            Dictionary<string, double> dic_M = new Dictionary<string, double>();
            dic_M["msum"] = 0.0;
            var result_M = myCollection.Group(query, BsonJavaScript.Create("function(doc){  var date = new Date(doc.add_time); var dateKey = date.getFullYear()+'年'+(date.getMonth()+1)+'月'+date.getDate();  return {'day':dateKey}; }"), BsonDocument.Create(dic_M),
                                            BsonJavaScript.Create("function(obj,prev){prev.msum += obj.price;}"),
                                            BsonJavaScript.Create("function(obj){obj.sum=obj.msum;delete obj.sum;}")).ToList();

            List<vm_bangzhuan_detailModel> result = new List<vm_bangzhuan_detailModel>();
            if (result_M != null && result_M.Count > 0)
            {
                foreach (var item in result_M)
                {
                    double amount = Math.Round(Convert.ToDouble(item["msum"]), 2);
                    result.Add(new vm_bangzhuan_detailModel
                    {   
                        day = Convert.ToDateTime(item["day"]),
                        amount = amount
                    });
                }
            }

            result = result.OrderByDescending(x => x.day).ToList();

            return result;
        }
複製程式碼