C#对MongDB取数据的常用代码

1、使用聚合取最新的实时数据(每一个测站有多条数据,取日期最新的数据。也就是每个测站取最新的值)

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 collection = MoDataBase.GetCollection<BsonDocument>(tablename);
 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();

2、普通的按照排序取最新的数据

如果一个测站一个表名

/// <summary>
        /// 获取数据库中每条数据对应的时间放到图表的横坐标上
        /// </summary>
        /// <param name="StatioID">监测站ID</param>
        /// <param name="PullutionID">指标类型</param>
        /// <returns></returns>
        public static List<string> GetChartData(string StatioID, string PullutionID,string StartTime,string EndTime)
        {
            List<string> XData = new List<string>();
            if (ConnectionString == null) OnCreateDB();
            MoDataBase = MoClient.GetDatabase("SSMonitor");
            BsonDocument bsonDoc = new BsonDocument();
            bsonDoc.Add("TimeData", new BsonDocument() { { "$gte", DateTimeToInt(StartTime) }, { "$lte", DateTimeToInt(EndTime) } });
            var collection = MoDataBase.GetCollection<BsonDocument>(string.Format("{0}_{1}_Day", StatioID, PullutionID));
            var sort = Builders<BsonDocument>.Sort.Ascending("TimeData");
            var list = collection.Find(bsonDoc).Sort(sort).ToList();
            foreach (BsonDocument bsondoc in list)
            {
                string time = bsondoc.GetElement("MonitorTime").Value.ToString();
                XData.Add(time);
            }
            return XData;
        }

 

posted @ 2018-05-24 15:20  风轻云淡wjr  阅读(235)  评论(13编辑  收藏  举报