ASP.NET MongoDB数据库操作类

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: 1、Web.config文件中配置数据库连接信息,如下代码: 2、MongoDBHelper操作类,如下代码:using System;using System.

1、Web.config文件中配置数据库连接信息,如下代码:

<appSettings>
    <!--连接MongoDB数据库连接字符串开始-->
    <add key="MongoIP" value="192.168.33.162" />
    <add key="MongoDatabase" value="ADS5_HNXY" />
    <!--MongoDB集群名称,单台MongoDB时请注释掉下面行的配置-->
    <!--<add key="ReplicaSetName" value="atrepl"/>-->
    <add key="MongoUser" value=""/>
    <add key="MongoPassword" value=""/>
    <!--连接MongoDB数据库连接字符串结束 -->
</appSettings>


2、MongoDBHelper操作类,如下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;
using AT.Business.IDAO;
using AT.Business.DAL;
using AT_DataShiftService;


namespace BAL.DBHelper
{
    /// <summary>
    /// MongoDB数据库操作类
    /// </summary>
    public class MongoData
    {


        #region 属性列表


        private static string ip = System.Configuration.ConfigurationManager.AppSettings["MongoIP"];
        private static string dbname = System.Configuration.ConfigurationManager.AppSettings["MongoDatabase"];
        private static string user = System.Configuration.ConfigurationManager.AppSettings["MongoUser"];
        private static string pwd = System.Configuration.ConfigurationManager.AppSettings["MongoPassword"];
        private static string myReplicaSetName = System.Configuration.ConfigurationManager.AppSettings["ReplicaSetName"];


        private static ReadPreference myReadPreference = ReadPreference.SecondaryPreferred;


        //两个不同的表名
        private const string _ADS5 = "ads5";
        private const string _POWERPARAMETERS = "PowerParameters";


        private static AT_System_IDAO systemidao = new AT_System_Dal();


        #endregion


        #region MongoDB权限认证


        /// <summary>
        ///  MongoDB权限认证
        /// </summary>
        /// <returns></returns>
        public static MongoDatabase getDatabase()
        {
            MongoClientSettings setting = new MongoClientSettings();
            if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pwd))
            {
                //Logger.Log.Info("MongoDB开启权限访问 " + user + ":" + pwd);
                List<MongoCredential> lstCredential = new List<MongoCredential>();
                lstCredential.Add(MongoCredential.CreateCredential(dbname, user, pwd));
                setting.Credentials = lstCredential;
            }
            setting.Server = new MongoServerAddress(ip);
            if (!string.IsNullOrEmpty(myReplicaSetName))
            {
                //Logger.Log.Info("MongoDB开启集群模式 " + myReplicaSetName);
                setting.ConnectionMode = ConnectionMode.ReplicaSet;
                setting.ReplicaSetName = myReplicaSetName;
                setting.ReadPreference = myReadPreference;
            }
            //MongoClient client = new MongoClient(QJBL.MongoDBConn);
            var client = new MongoClient(setting);
            MongoServer server = client.GetServer();
            MongoDatabase database = server.GetDatabase(dbname);
            return database;
        }


        #endregion


        #region 获取MySQL中对应表具列表信息 2017-05-17


        /// <summary>
        ///  获取MySQL中对应表具列表信息
        /// </summary>
        /// <returns></returns>
        public static DataTable GetMeterList()
        {
            return systemidao.GetMeterList();
        }


        #endregion


        #region 获取每个整点需要上传的表具读数 2017-05-17


        /// <summary>
        /// 获取每个整点需要上传的表具读数
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static DataTable AT_Up_EnergyValue4WJW(string datetime)
        {
            DataTable dt = GetMeterList();
            DataTable newDT = new DataTable();
            newDT.Columns.Add("BuildID", typeof(string));
            newDT.Columns.Add("CollectionID", typeof(string));
            newDT.Columns.Add("MeterID", typeof(string));
            newDT.Columns.Add("EnergyValue", typeof(double));
            foreach (DataRowView drv in dt.DefaultView)
            {
                DataRow row = newDT.NewRow();
                if (drv["F_MeasureClassify"].ToString() == "04" || drv["F_MeasureClassify"].ToString() == "14")
                {
                    //从MongoDB中的PowerParameters中取数
                    row["BuildID"] = drv["BuildID"].ToString();
                    row["CollectionID"] = drv["CollectionID"].ToString();
                    row["MeterID"] = drv["MeterID"].ToString();
                    double rawValue = GetDataFromPowerParameters(drv["F_MeterID"].ToString(), DateTime.Parse(datetime), drv["F_ValueType"].ToString());
                    //这里去除的可能是负数,要做绝对值转换
                    double absValue = Math.Abs(rawValue);
                    row["EnergyValue"] = double.Parse(drv["F_Ratio"].ToString()) * absValue * 0.0036;
                    WriteLog(drv["F_MeterID"].ToString() + "\t" + datetime + "\t" + (double.Parse(drv["F_Ratio"].ToString()) * absValue * 0.0036) + "\r");
                    newDT.Rows.Add(row);
                }
                else
                {
                    //从MongoDB中的ADS5中取数
                    row["BuildID"] = drv["BuildID"].ToString();
                    row["CollectionID"] = drv["CollectionID"].ToString();
                    row["MeterID"] = drv["MeterID"].ToString();
                    double rawValue = GetDataFromADS5(drv["F_TagName"].ToString(), DateTime.Parse(datetime));


                    double absValue = Math.Abs(rawValue);
                    row["EnergyValue"] = double.Parse(drv["F_Ratio"].ToString()) * absValue;
                    WriteLog(drv["F_TagName"].ToString() + "\t" + datetime + "\t" + double.Parse(drv["F_Ratio"].ToString()) * absValue + "\r");
                    newDT.Rows.Add(row);
                }
            }
            return newDT;
        }


        #endregion


        #region 当F_MeasureClassify不为‘04’和‘14’时,从ADS5表中获取表头示数 2017-08-03


        /// <summary>
        /// F_CaclType = 0 ,从ADS5表中获取数据
        /// </summary>
        /// <param name="TagName"></param>
        /// <param name="DateTime"></param>
        /// <returns></returns>
        public static double GetDataFromADS5(string TagName, DateTime DateTime)
        {
            MongoDatabase db = MongoData.getDatabase();
            //获得Users集合,如果数据库中没有,先新建一个
            MongoCollection col = db.GetCollection(_ADS5);


            var query = Query.And(
            Query.EQ("TagName", TagName),
            Query.EQ("DateTime", DateTime)
            );
            List<BsonDocument> documents = col.FindAs<BsonDocument>(query).ToList();
            //做异常处理
            if (documents.Count != 0)
            {
                BsonElement element = documents[0].GetElement("Value");
                return double.Parse(element.Value.ToString());
            }
            else
            {
                //直至可以获取到上一个有数据的时刻 2017-08-03
                int index = 0;
                do
                {
                    index++;
                    DateTime NewDateTime = DateTime.AddHours(-1 * index);
                    query = Query.And(
                        Query.EQ("TagName", TagName),
                        Query.EQ("DateTime", NewDateTime)
                     );
                    documents = col.FindAs<BsonDocument>(query).ToList();
                } while (documents.Count == 0);


                BsonElement element = documents[0].GetElement("Value");
                return double.Parse(element.Value.ToString());
            }
        }


        #endregion


        #region 当F_MeasureClassify为‘04’或‘14’时,从PowerParameters表中获取表头示数 2017-08-03


        /// <summary>
        /// 从PowerParameters表中获取数据
        /// </summary>
        /// <param name="TagName"></param>
        /// <param name="DateTime"></param>
        /// <returns></returns>
        public static double GetDataFromPowerParameters(string MeterID, DateTime DateTime, string ValueType)
        {
            MongoDatabase db = MongoData.getDatabase();
            //获得Users集合,如果数据库中没有,先新建一个
            MongoCollection col = db.GetCollection(_POWERPARAMETERS);
            var query = Query.And(
             Query.EQ("MeterID", MeterID),
             Query.EQ("DateTime", DateTime)
             );
            List<BsonDocument> documents = col.FindAs<BsonDocument>(query).ToList();
            //做异常处理
            if (documents.Count != 0)
            {
                BsonElement element = documents[0].GetElement(ValueType);
                return double.Parse(element.Value.ToString());
            }
            else
            {
                //直至可以获取到上一个有数据的时刻 2017-08-03
                int index = 0;
                do
                {
                    index ++;
                    DateTime NewDateTime = DateTime.AddHours(-1 * index);
                    query = Query.And(
                         Query.EQ("MeterID", MeterID),
                         Query.EQ("DateTime", NewDateTime)
                    );
                    documents = col.FindAs<BsonDocument>(query).ToList();
                } while (documents.Count == 0);


                BsonElement element = documents[0].GetElement(ValueType);
                return double.Parse(element.Value.ToString());
            }
        }


        #endregion


        #region 日志记录


        /// <summary>
        /// 
        /// </summary>
        /// <param name="log"></param>
        public static void WriteLog(string log)
        {
            string spath1 = System.AppDomain.CurrentDomain.BaseDirectory + @"\GetInterupt.Log";
            string spath = System.AppDomain.CurrentDomain.BaseDirectory + @"\" + DateTime.Now.ToString("yyyy") + @"\GetInterupt" + DateTime.Now.ToString("MM") + ".Log";
            if (!FileC.IsExistFile(spath))
            {
                FileC.CreateDirectory(FileC.GetDirectoryName(spath));
                FileC.CreateFile(spath);
                FileC.WriteText(spath1, "");
            }
            FileC.AppendText(spath, log + "\r\n");
            FileC.AppendText(spath1, log + "\r\n");
        }

        #endregion

    }
}



    

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
27天前
|
运维 监控 NoSQL
【MongoDB 复制集秘籍】Secondary 同步慢怎么办?深度解析与实战指南,让你的数据库飞速同步!
【8月更文挑战第24天】本文通过一个具体案例探讨了MongoDB复制集中Secondary成员同步缓慢的问题。现象表现为数据延迟增加,影响业务运行。经分析,可能的原因包括硬件资源不足、网络状况不佳、复制日志错误等。解决策略涵盖优化硬件(如增加内存、升级CPU)、调整网络配置以减少延迟以及优化MongoDB配置(例如调整`oplogSize`、启用压缩)。通过这些方法可有效提升同步效率,保证系统的稳定性和性能。
39 4
|
1月前
|
监控 NoSQL MongoDB
MongoDB数据库的索引管理技巧
【8月更文挑战第20天】MongoDB数据库的索引管理技巧
42 1
|
1月前
|
监控 NoSQL MongoDB
mongodb数据库 使用技巧
【8月更文挑战第20天】mongodb数据库 使用技巧
34 1
|
1月前
|
SQL 开发框架 数据库
".NET开发者的超能力:AgileEAS.NET ORM带你穿越数据库的迷宫,让数据操作变得轻松又神奇!"
【8月更文挑战第16天】AgileEAS.NET是面向.NET平台的企业应用开发框架,核心功能包括数据关系映射(ORM),允许以面向对象方式操作数据库,无需编写复杂SQL。通过继承`AgileEAS.Data.Entity`创建实体类对应数据库表,利用ORM简化数据访问层编码。支持基本的CRUD操作及复杂查询如条件筛选、排序和分页,并可通过导航属性实现多表关联。此外,提供了事务管理功能确保数据一致性。AgileEAS.NET的ORM简化了数据库操作,提升了开发效率和代码可维护性。
44 5
|
17天前
|
SQL 存储 关系型数据库
C#一分钟浅谈:使用 ADO.NET 进行数据库访问
【9月更文挑战第3天】在.NET开发中,与数据库交互至关重要。ADO.NET是Microsoft提供的用于访问关系型数据库的类库,包含连接数据库、执行SQL命令等功能。本文从基础入手,介绍如何使用ADO.NET进行数据库访问,并提供示例代码,同时讨论常见问题及其解决方案,如连接字符串错误、SQL注入风险和资源泄露等,帮助开发者更好地利用ADO.NET提升应用的安全性和稳定性。
48 6
|
1月前
|
JSON NoSQL Ubuntu
在Ubuntu 14.04上如何备份、恢复和迁移MongoDB数据库
在Ubuntu 14.04上如何备份、恢复和迁移MongoDB数据库
56 1
|
20天前
|
C# 开发者 Windows
全面指南:WPF无障碍设计从入门到精通——让每一个用户都能无障碍地享受你的应用,从自动化属性到焦点导航的最佳实践
【8月更文挑战第31天】为了确保Windows Presentation Foundation (WPF) 应用程序对所有用户都具备无障碍性,开发者需关注无障碍设计原则。这不仅是法律要求,更是社会责任,旨在让技术更人性化,惠及包括视障、听障及行动受限等用户群体。
43 0
|
20天前
|
数据库 C# 开发者
WPF开发者必读:揭秘ADO.NET与Entity Framework数据库交互秘籍,轻松实现企业级应用!
【8月更文挑战第31天】在现代软件开发中,WPF 与数据库的交互对于构建企业级应用至关重要。本文介绍了如何利用 ADO.NET 和 Entity Framework 在 WPF 应用中访问和操作数据库。ADO.NET 是 .NET Framework 中用于访问各类数据库(如 SQL Server、MySQL 等)的类库;Entity Framework 则是一种 ORM 框架,支持面向对象的数据操作。文章通过示例展示了如何在 WPF 应用中集成这两种技术,提高开发效率。
36 0
|
20天前
|
Java 前端开发 Spring
技术融合新潮流!Vaadin携手Spring Boot、React、Angular,引领Web开发变革,你准备好了吗?
【8月更文挑战第31天】本文探讨了Vaadin与Spring Boot、React及Angular等主流技术栈的最佳融合实践。Vaadin作为现代Java Web框架,与其他技术栈结合能更好地满足复杂应用需求。文中通过示例代码展示了如何在Spring Boot项目中集成Vaadin,以及如何在Vaadin项目中使用React和Angular组件,充分发挥各技术栈的优势,提升开发效率和用户体验。开发者可根据具体需求选择合适的技术组合。
28 0