Home Database Mysql Tutorial c#链接mongDB集群实战开发3

c#链接mongDB集群实战开发3

Jun 07, 2016 pm 03:56 PM
Actual combat develop Link cluster

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>
Copy after login

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); 这句代码可以根据自己需要修改。
Copy after login

其他没有什么注意的地方

数据插入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;
        }
Copy after login

读取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;
        } 
Copy after login

以上是插入和读取代码。

后面运行效果如下

\

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

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to download links starting with 115://? Download method introduction How to download links starting with 115://? Download method introduction Mar 14, 2024 am 11:58 AM

Recently, many users have been asking the editor, how to download links starting with 115://? If you want to download links starting with 115://, you need to use the 115 browser. After you download the 115 browser, let's take a look at the download tutorial compiled by the editor below. Introduction to how to download links starting with 115:// 1. Log in to 115.com, download and install the 115 browser. 2. Enter: chrome://extensions/ in the 115 browser address bar, enter the extension center, search for Tampermonkey, and install the corresponding plug-in. 3. Enter in the address bar of 115 browser: Grease Monkey Script: https://greasyfork.org/en/

How to get the WeChat video account link? How to add product links to WeChat video account? How to get the WeChat video account link? How to add product links to WeChat video account? Mar 22, 2024 pm 09:36 PM

As part of the WeChat ecosystem, WeChat video accounts have gradually become an important promotion tool for content creators and merchants. Getting links to video accounts on this platform is crucial for sharing and disseminating content. The following will introduce in detail how to obtain the WeChat video account link and how to add product links to the video account to improve the dissemination effect of the content. 1. How to get the WeChat video account link? After posting a video on your WeChat video account, the system will automatically create a video link. Authors can copy the link after publishing to facilitate sharing and dissemination. After logging in to your WeChat video account, you can browse the homepage of your video account. On the home page, each video is accompanied by a corresponding link so you can copy or share it directly. 3. Search video account: Enter the video account name in the WeChat search box

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

What are the requirements for a video link? How to link the video account with goods? What are the requirements for a video link? How to link the video account with goods? Mar 07, 2024 pm 01:13 PM

With the popularity of short video platforms, more and more creators are beginning to use video accounts to create and promote content. Video accounts can not only showcase personal talents, but also realize commercial monetization through product links. However, to add a link to a video account, certain conditions must be met. 1. What are the requirements for a video link? Video account authentication is a prerequisite for adding links to your video account. Currently, major short video platforms such as Douyin and Kuaishou provide certification services, which mainly include two types: personal certification and institutional certification. Personal certification requires the submission of real identity information, while institutional certification requires the provision of certification materials from relevant companies or organizations. After completing the authentication, users can add links to their video accounts to enhance the credibility and authority of their accounts. One of the video link

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

PHP Practical: Code Example to Quickly Implement Fibonacci Sequence PHP Practical: Code Example to Quickly Implement Fibonacci Sequence Mar 20, 2024 pm 02:24 PM

PHP Practice: Code Example to Quickly Implement the Fibonacci Sequence The Fibonacci Sequence is a very interesting and common sequence in mathematics. It is defined as follows: the first and second numbers are 0 and 1, and from the third Starting with numbers, each number is the sum of the previous two numbers. The first few numbers in the Fibonacci sequence are 0,1,1.2,3,5,8,13,21,...and so on. In PHP, we can generate the Fibonacci sequence through recursion and iteration. Below we will show these two

How to link on Doudian - Tutorial on linking on Doudian How to link on Doudian - Tutorial on linking on Doudian Mar 06, 2024 am 08:40 AM

Many friends still don’t know how to link on Doudian, so the editor below will explain the tutorial on how to link on Doudian. If you are in need, hurry up and take a look. I believe it will be helpful to everyone. Step 1: First open the Doudian computer terminal and enter "Window Product Management" on the left column, as shown in the picture. Step 2: Then click "Add Product" in the upper right corner, as shown in the picture. Step 3: Then copy and paste our product link, as shown in the picture. Step 4: Then click "Confirm Add", as shown in the picture. Step 5: Finally enter the introduction, pictures and other information, and then click "Confirm" to link on Douyin, as shown in the picture. The above is the entire content of how to add links to Doudian brought to you by the editor. I hope it can be helpful to everyone.

See all articles