search
HomeDatabaseMysql TutorialMongodbConnectionString

本文档描述定义的URI格式之间,以及应用程序和MongoDB实例的连接,参考官方MongoDB的驱动。 原文 :http://docs.mongodb.org/manual/reference/connection-string/#connections-connection-options 标准连接字符串格式 本节描述的标准格式连接MongoDBURI用于

本文档描述定义的URI格式之间,以及应用程序和MongoDB实例的连接,参考官方MongoDB的驱动。

原文 :http://docs.mongodb.org/manual/reference/connection-string/#connections-connection-options

标准连接字符串格式

本节描述的标准格式连接MongoDBURI用于连接MongoDB数据库服务器。所有官方MongoDB的格式都是相同的驱动程序。对于驱动和驱动的链接文档的列表,看到MongoDB驱动和客户端库(MongoDB Drivers and Client Libraries)

以下是标准的链接方式

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

参数说明:

mongodb://字符串链接的标准格式

username:password@

可选的,一般默认是没有名称和密码的,只有在MongoDB服务器使用了身份验证时才出现。

/database

可选的,如果链接的字符串中包含了验证身份的用户名和密码,则数据库是必须要有的。若没有包含数据库名称,默认是链接admin的数据库

?options

链接特定选项。如果没有指定链接特定的数据库名称,必须在主机名后面加"/",并且在optin的前面以问号形式开头"?".

实例:

mongodb://db1.example.net,db2.example.net:2500/?replicaSet=test

继续查找发现了另一篇文章。只做重点翻译:

内部认证

当你只需要一个用户,它在连接字符串中指定这是可能的。

var connectionString ="mongodb://user1:password1@localhost/test";
var mongoClient = newMongoClient(connectionString);
 
注意: 如果你不指定一个数据库连接字符串,默认的数据库是“admin”数据库.

看到这里心里狂喜,终于可以进行配置文件的设置了,但是发现c#的驱动并不支持这样的编写,于是又是一个失落。

链接原理:

链接数据库,官方提供了两种线程安全的方式,一个是MongoClient, 另一个是MongoServer,都是线程安全的,自动进行锁定的。

利用服务端类链接数据库

// Create server settings to passconnection string, timeout, etc.
MongoServerSettingssettings =newMongoServerSettings();
settings.Server = new MongoServerAddress("localhost",27017);
// Create server object tocommunicate with our server
MongoServer server = new MongoServer(settings);
// Get our databaseinstance to reach collections and data
var database = server.GetDatabase("MessageDB");

客户端类链接数据库的实例

var client = new MongoClient("mongodb://localhost:27017");
var server = client.GetServer();
var database = server.GetDatabase("foo");
var collection = database.GetCollection("bar");

以上的两种链接方式我都做个测试。并且都可以用。这是一般更倾向于客户端的链接方式。

通过查找Api,发现客户端的类的构造方法还有其他的

  public MongoClient();
        public MongoClient(MongoClientSettingssettings);
        public MongoClient(MongoUrl url);
        public MongoClient(stringconnectionString);

我们通常用的是string字符串的链接,这次对MongoClientSettings进行的深度的查找调用发MongoClientSettings 是可以进行更多的参数设置的,和Option类似,于是找到了解决方案,通过配置文件对MongoClientSettings进行参数设置。

默认情况下,最大链接池是100,最小是0,数据库链接是本地的。下面我们看测试

MongoClientSettings settingsclient = newMongoClientSettings();//实例化客户端设置类

\

 红色划线部分是默认的参数,当我们不填写任何参数,驱动程序是进行默认的参数设置的。

通过客户端类的参数设置可以发现已经有所不同了。

\

那代码是如何编写的呢

#region 读取配置文件信息

            //获取链接池大小

            int connectionPool =Convert.ToInt32(ConfigurationManager.AppSettings["connectionPool"]);

            int minpool =Convert.ToInt32(ConfigurationManager.AppSettings["minpool"]);

            string hostname =ConfigurationManager.AppSettings["hostname"];

            Int32 port =Convert.ToInt32(ConfigurationManager.AppSettings["port"]);

            string database =ConfigurationManager.AppSettings["database"];
 
            #endregion
 
 if (String.IsNullOrEmpty(ConnectionString))

            {

                throw newArgumentNullException("Connection string not found.");

            }

   #region 客户端类设置

            MongoServerAddress ipaddress = newMongoServerAddress(hostname, port);//设置服务器的ip和端口

            MongoClientSettings settingsclient= new MongoClientSettings();//实例化客户端设置类

            settingsclient.Server =ipaddress;//端口赋值

           settingsclient.MaxConnectionPoolSize = connectionPool;

           settingsclient.MinConnectionPoolSize = minpool;

            settingsclient.ConnectionMode =0;//链接模式设置

           // MongoUrl url=newMongoUrl(ConnectionString);

            MongoClient client = newMongoClient(settingsclient);//调用客户端类构造函数设置参数

            MongoServer server =client.GetServer();//服务端获取客户端参数

            DB =server.GetDatabase(database);//获取数据库名称

            #endregion 

刚开始我也是不知道如何进行参数赋值,只是在一步步的操作中发现参数是有类型的,一些类型是一些引用类,就需要实例化赋值。所以才有最后看起来很多的参数。

配置文件中的信息

<addkey="connectionPool" value="1000"/><!--连接池设置-->

    <add key="hostname"value="192.168.24.249"/>

    <add key="port"value="27017"/>

    <add key="database"value="DB3"/>

    <add key="minpool"value="300"/>

  </appSettings>

当然了客户端的方式写出来了。服务端也就容易的很多了

#region 服务端链接设置

            MongoServerSettings mongoSetting =new MongoServerSettings();

            //mongoSetting.Server = newMongoServerAddress(ConnectionString, connectionPool);

            mongoSetting.MaxConnectionPoolSize= connectionPool;//设定最大连接池

            mongoSetting.Server = newMongoServerAddress(hostname, port);

            MongoServer server =MongoServer.Create(mongoSetting);//创建连接数据文件

            DB = server.GetDatabase(database);

            #endregion 

认识:

由于该数据库的参考资料比较少,所以多数资料还是外文,刚开始看到很是惊讶,如此多的英语能看的明白么。但是只要心境平静,一切都是可以的。通过基本的查找和一些外文论坛了解的基本的设置。很像SQL的设置,但是又不同,需要进行代码设置,这是这个代码的参数可以写在配置文件中。这次的资料查找我深刻认识到,英语是非常非常重要的工具,如果你想更深入的了解,英语是必不可少的利器。

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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

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 Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools