zoukankan      html  css  js  c++  java
  • 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;
            }
  • 相关阅读:
    php 高精度计算函数
    CSS 文本溢出显示省略号样式
    Vue import、export及export default示例详解,附带如何实现全局调用
    利用高德API获取最新的省市区数据
    TP5 基类验证器
    php 两种递归方法
    新建PO類型ZFA的固定資產時灰掉 GR Non-Valuated
    MRP 參數設置
    info record
    kill procedure in os level
  • 原文地址:https://www.cnblogs.com/wjr0117/p/9083067.html
Copyright © 2011-2022 走看看