C#操作mongodb(聚合函数)-分组找出每组的最大值

 public static void OnQuery_QXData(string DBName, string tablename,string layername)
        {
            if (ConnectionString == null) OnCreateDB();
            MoDataBase = MoClient.GetDatabase(DBName);
            var collection = MoDataBase.GetCollection<BsonDocument>(tablename);           

            //{$group:{_id:{stationID:"$stationID",stationName:"$stationName"},TimeData:{$max:"$TimeData"},eValue:{$last:"$eValue"}}}           

            var group = new BsonDocument {

                {"_id",new BsonDocument
                {
                    {"stationID","$stationID"},
                    {"stationName","$stationName" }
                }
        },
                //{"stationID",new BsonDocument{ { "stationID", "$stationID" } } },
                {"stationID",new BsonDocument("$last","$stationID")},
                { "TimeData",new BsonDocument("$max","$TimeData")},
                {"eValue" ,new BsonDocument("$last","$eValue")}
            };
            var list = collection.Aggregate().Group(group).ToListAsync().Result;
            double value = 0.0;
            foreach (BsonDocument bsondoc in list)
            {
               
                double  evalue = double.TryParse(bsondoc.GetElement("eValue").Value.ToString(),out value)?value:0;
                string stationid = bsondoc.GetElement("stationID").Value.ToString();              
            }
        }
    }
}

posted @ 2018-05-10 15:55  风轻云淡wjr  阅读(693)  评论(0编辑  收藏  举报