search
HomeDatabaseMysql Tutorialc#链接mongDB集群实战开发3

c# 链接mongDB集群 一 了解mongdb 二 部署集群 三 C#链接mongdb 完成测试 C#链接mongdb 完成测试 此章节继续我们上一章节将的我们开始用程序去链接mondbdb,大家都知道我们链接sqlserver其实用的是微软自己写的驱动。它已经封装了一些对象,要我们去链接。但

c# 链接mongDB集群

一 了解mongdb

二 部署集群

三 C#链接mongdb 完成测试 

C#链接mongdb 完成测试

此章节继续我们上一章节将的我们开始用程序去链接mondbdb,大家都知道我们链接sqlserver其实用的是微软自己写的驱动。它已经封装了一些对象,要我们去链接。但是我们链接mondbdb 同样需要一些对象,这个mongdb官网有说明,可以自己去看看或者直接下载我的这里下载 或者在第一章节有些伙伴们已经下载好了

开发驱动文件夹 在 mongo-csharp-driver-master\mongo-csharp-driver-master\src SRC下面看到驱动项目这里注意,我下载是vs2012的项目,同学们可以根据自己的需要替换net framework 版本

打开项目之后看到 如图所示

\

编译项目得到

MongoDB.Bson.dll

MongoDB.Driver.dll

创建项目,项目配置文件如下

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="LogLevel" value="trace" />
    <add key="LogPath" value="E:\Tools\mongdb\FrmMongDB\FrmMongDB\logs" />
    
    <!--MongDb配置begin-->
    <add key="MongReplicaSetName" value="zuomm"/><!--设置副本集名称-->
    <add key="MongoServerAddress" value="127.0.0.1:1111|127.0.0.1:2222|127.0.0.1:3333"/><!--mongdb集群列表-->
    <add key="TimeOut" value="60"/><!--mongdb集群链接超时时间-->
    <!--MongDb配置end-->
  </appSettings>

</configuration>

LogLevel 为自定义 日记级别 ,这个后面看我的代码

LogPath 为日志路径

MongReplicaSetName 为副本集名称,其实就是建立集群的时候取的名字。

MongoServerAddress 为集群机器ip列表,我这里是自己的机器开了不同的端口来区别,你可以改成局域网ip

TimeOut 超时时间,默认貌似是3秒,我这里设置60秒方便调试

链接集群主要代码

 /// <summary>
        /// 取得数据库连接字符串
        /// </summary>
        /// <param name="connName">App.Config文件中AppSettings节中 AppSettings 对应的name</param>
        /// <returns>数据库连接字符串</returns>
        private static MongoServer GetConnStr()
        {
            List<MongoServerAddress> servers = new List<MongoServerAddress>();
            string reg = @"^(?&#39;server&#39;\d{1,}.\d{1,}.\d{1,}.\d{1,}):(?&#39;port&#39;\d{1,})$";
            string[] ServerList = ConfigurationManager.AppSettings["MongoServerAddress"].Trim().Split(&#39;|&#39;);
            foreach (string server in ServerList)
            {
                MatchCollection mc = Regex.Matches(server, reg);
                if (mc != null && mc.Count > 0)
                    servers.Add(new MongoServerAddress(mc[0].Groups["server"].ToString(), Convert.ToInt32(mc[0].Groups["port"].ToString())));
            }

            if (servers == null || servers.Count < 1)
                return null;

            MongoClientSettings set = new MongoClientSettings();

            set.Servers = servers;

            set.ReplicaSetName = ConfigurationManager.AppSettings["MongReplicaSetName"].Trim();//设置副本集名称

            int TimeOut =ConvertUtil.ParseInt(ConfigurationManager.AppSettings["TimeOut"].Trim());//设置副本集名称

            set.ConnectTimeout = new TimeSpan(0, 0, 0, TimeOut, 0);//设置超时时间为5秒

            set.ReadPreference = new ReadPreference(ReadPreferenceMode.SecondaryPreferred);

            MongoClient client = new MongoClient(set);

            return client.GetServer();
        }
set.ReadPreference = new ReadPreference(ReadPreferenceMode.SecondaryPreferred); 这句代码可以根据自己需要修改。

其他没有什么注意的地方

数据插入mongdb代码

    /// <summary>
        /// MongDB 批量insert语句
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="_databaseName">数据库名称</param>
        /// <param name="_collectionName">表名称</param>
        /// <param name="entitys">对象</param>
        /// <param name="errorMsg">返回错误</param>
        /// <returns></returns>
        public static IEnumerable<SafeModeResult> Execute<T>(string _databaseName, string _collectionName, IEnumerable<T> entitys, out string errorMsg)
        {
            errorMsg = string.Empty;
            //取得数据库连接
            IEnumerable<SafeModeResult> result = null;

            try
            {
                if (null == entitys)
                    return null;
                //获取连接的服务器集群
                _server = GetConnStr();

                //获取数据库或者创建数据库(不存在的话)。
                MongoDatabase database = _server.GetDatabase(_databaseName);

                using (_server.RequestStart(database))//开始连接数据库。
                {
                    MongoCollection<T> myCollection = database.GetCollection<T>(_collectionName);
                    result = myCollection.InsertBatch<T>(entitys);
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.ToString();
            }
            finally
            {
            }

            //记录日志
            if (!string.IsNullOrEmpty(errorMsg))
            {
                LogUtil.Error("CommonLib.DbAccess.MongDBAccess", "Execute", errorMsg + "\n\r\t");
            }

            return result;
        }

读取mongdb数据代码

/// <summary>
        /// 如果不清楚具体的数量,一般不要用这个函数。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string _databaseName, string collectionName,out string errorMsg)
        {
            errorMsg = string.Empty;
            List<T> result = new List<T>();
            try
            {
                //获取连接的服务器集群
                _server = GetConnStr();

                //获取数据库或者创建数据库(不存在的话)。
                MongoDatabase database = _server.GetDatabase(_databaseName);
               
                using (_server.RequestStart(database))//开始连接数据库。
                {
                    MongoCollection<T> myCollection = database.GetCollection<T>(collectionName);
                    result.AddRange(myCollection.FindAll());
                }
            }
            catch (Exception ex )
            {
                errorMsg = ex.ToString();
            }
            //记录日志
            if (!string.IsNullOrEmpty(errorMsg))
            {
                LogUtil.Error("CommonLib.DbAccess.MongDBAccess", "GetAll", errorMsg + "\n\r\t");
            }
            return result;
        } 

以上是插入和读取代码。

后面运行效果如下

\

我这里插入了10w条数据 人然后读取10w条数据。效率比sqlserver是快很多。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.