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;
            }
  • 相关阅读:
    VHDL硬件描述语言(三)——基本数据对象和数据类型
    VHDL硬件描述语言(二)——子程序
    VHDL硬件描述语言(一)——基本结构
    C#类
    C#基本语法
    C#的简单数据类型
    C#与.NET
    ARP
    IPv6
    以太网
  • 原文地址:https://www.cnblogs.com/wjr0117/p/9083067.html
Copyright © 2011-2022 走看看