1.连接方式
连接 URI
连接 URI(也称为连接字符串)可告知驱动程序如何连接到 MongoDB 部署,以及连接后如何进行操作。(例:"mongodb://username:password@host[:port]/defaultauthdb?<options>")
标准连接字符串包括以下部分:
| 必需。将其标识为标准连接格式中字符串的前缀。 |
| 可选。身份验证凭证。如果包含这些内容,客户端将根据 |
| 必需。运行 MongoDB 的主机和可选端口号。如果未包含端口号,则驱动程序将使用默认端口 |
| 可选。如果连接字符串包含 |
| 可选。将连接特定选项指定为 |
要使用连接 URI,请将其作为字符串传递给 MongoClient
构造函数。在以下示例中,驱动程序使用示例连接 URI 连接到位于 localhost
的端口 27017
上的 MongoDB 实例:
using MongoDB.Driver;
// Sets the connection URI
//const string connectionUri = "mongodb://localhost:27017";
const string connectionUri = "mongodb+srv://sample.host:27017/?connectTimeoutMS=60000&tls=true";
// Creates a new client and connects to the server
var client = new MongoClient(connectionUri);
客户端重用
由于每个
MongoClient
代表一个数据库连接池,因此大多数应用程序只需要单一MongoClient
实例,甚至在多个请求中也是如此。
MongoClientSettings
您可以使用 MongoClientSettings
对象在代码中(而不是在连接 URI 中)配置连接。要使用 MongoClientSettings
对象,请创建此类的实例并将其作为参数传递给 MongoClient
构造函数。
在以下示例中,驱动程序使用 MongoClientSettings
对象连接到 localhost
的端口 27017
上的 MongoDB 实例:
using MongoDB.Driver;
// Creates a MongoClientSettings object
var settings = new MongoClientSettings()
{
Scheme = ConnectionStringScheme.MongoDB,
Server = new MongoServerAddress("localhost", 27017)
};
// Creates a new client and connects to the server
var client = new MongoClient(settings);
下表列出了 MongoClientSettings
类中可用的每个连接选项,以及如何在连接字符串中实现相同的结果(如可能)。如果 MongoClientSettings
属性映射到连接字符串中的多个选项,则连接 URI 示例将显示所有相关选项。
如果将查询参数用于时间段,其值必须以毫秒为单位。例如,要指定 60 秒,请使用值
60000
。如果将MongoClientSettings
对象用于时间段,请使用相应的TimeSpan
值。
MongoClientSettings Property | Description | |||
---|---|---|---|---|
AllowInsecureTls | Specifies whether to relax TLS constraints as much as possible. This can include allowing invalid certificates or hostname mismatches. If this property is set to is set to Data Type: Default: Connection URI Example: | |||
ApplicationName | The app name the driver passes to the server in the client metadata as part of the connection handshake. The server prints this value to the MongoDB logs once the connection is established. The value is also recorded in the slow query logs and profile collections. Data Type: Default: Connection URI Example: | |||
AutoEncryptionOptions | Settings for automatic client-side encryption. Data Type: AutoEncryptionOptions Default: Connection URI Example: N/A | |||
ClusterConfigurator | Low-level configuration options for sockets, TLS, cluster, and others. Data Type: Action<ClusterBuilder> Default: Connection URI Example: N/A | |||
Compressors | The preferred compression types, in order, for wire-protocol messages sent to or received from the server. The driver uses the first of these compression types that the server supports. Data Type: CompressorConfiguration Default: Connection URI Example: | |||
ConnectTimeout | The length of time the driver tries to establish a single TCP socket connection to the server before timing out. DataType: Default: 30 seconds Connection URI Example: | |||
Credential | Settings for how the driver authenticates to the server. This includes authentication credentials, mechanism, source, and other settings. If you don't specify an authentication mechanism, the driver uses either
authentication mechanisms for available authentication mechanisms. Data Type: MongoCredential Default: Connection URI Example:
| |||
DirectConnection | Specifies whether to force dispatch all operations to the host. If you specify this option, the driver doesn't accept the DNS seed list connection format. You must use the standard connection URI format instead. This property must be set to host name. Data Type: Default: Connection URI Example: | |||
HeartbeatInterval | The interval between regular server-monitoring checks. Must be greater than or equal to 500 milliseconds. Data Type: Default: 10 seconds Connection URI Example: | |||
HeartbeatTimeout | The length of time a monitoring socket can be idle before timing out. Data Type: Default: Same value as Connection URI Example: | |||
IPv6 | Specifies whether the host address is in IPv6 format. Data Type: Default: Connection URI Example: | |||
IsFrozen | Indicates whether the settings have been frozen. Frozen settings can't be changed. This option is read-only. Data Type: Default: Connection URI Example: N/A | |||
LinqProvider | The LINQ provider to use. Data Type: LinqProvider Default: Connection URI Example: N/A | |||
LoadBalanced | Specifies whether the driver is connecting to a load balancer. You can set this property to
Data Type: Default: Connection URI Example: | |||
LocalThreshold | The latency window for server eligibility. If a server's round trip takes longer than the fastest server's round-trip time plus this value, the server isn't eligible for selection. Data Type: Default: 15 milliseconds Connection URI Example: | |||
LoggingSettings | The settings used for logging. Data Type: LoggingSettings Default: Connection URI Example: N/A | |||
MaxConnecting | The greatest number of connections a driver's connection pool may be establishing concurrently. Data Type: Default: Connection URI Example: | |||
MaxConnectionIdleTime | The length of time a connection can be idle before the driver closes it. Data Type: Default: 10 minutes Connection URI Example: | |||
MaxConnectionLifeTime | The length of time a connection can be pooled before expiring. Data Type: Default: 30 minutes Connection URI Example: | |||
MaxConnectionPoolSize | The greatest number of clients or connections the driver can create in its connection pool. This count includes connections in use. Data Type: Default: Connection URI Example: | |||
MinConnectionPoolSize | The number of connections the driver should create and keep in the connection pool even when no operations are occurring. This count includes connections in use. Data Type: Default: Connection URI Example: | |||
ReadConcern | The client's default read concern. See read concern for more information. Data Type: ReadConcern Default: Connection URI Example: | |||
ReadEncoding | The UTF-8 encoding to use for string deserialization. Strict encoding will throw an exception when an invalid UTF-8 byte sequence is encountered. Data Type: Default: Strict encoding Connection URI Example: N/A | |||
ReadPreference | The client's default read-preference settings. longest replication lag, in wall-clock time, that a secondary can experience and still be eligible for server selection. Specifying See read preference for more information. Data Type: ReadPreference Default: Connection URI Example:
You can include the | |||
ReplicaSetName | The name of the replica set to connect to. Data Type: Default: Connection URI Example: | |||
RetryReads | Enables retryable reads. Data Type: Default: Connection URI Example: | |||
RetryWrites | Enables retryable writes. Data Type: Default: Connection URI Example: | |||
Scheme | Specifies whether to use the standard connection string format ( or the DNS seed list format ( See the MongoDB Manual for more information about connection string formats. If the try to use the DNS seed list format, the .NET/C# Driver will throw an exception. Data Type: ConnectionStringScheme Default: Connection URI Example: | |||
Server | The host and port number where MongoDB is running. Data Type: MongoServerAddress Default: Connection URI Example: | |||
ServerApi | Allows opting into Stable API versioning. See the MongoDB Manual for more information about Stable API versioning. Data Type: ServerApi Default: Connection URI Example: N/A | |||
Servers | The cluster members where MongoDB is running. Data Type: IEnumerable<MongoServerAddress> Default: Connection URI Example: | |||
ServerSelectionTimeout | The length of time the driver tries to select a server before timing out. Data Type: Default: 30 seconds Connection URI Example: | |||
SocketTimeout | The length of time the driver tries to send or receive on a socket before timing out. Data Type: Default: OS default Connection URI Example: | |||
SrvMaxHosts | The greatest number of SRV results to randomly select when initially populating the seedlist or, during SRV polling, adding new hosts to the topology. You can use this property only if the connection-string scheme is set to to a replica set. Data Type: Default: Connection URI Example: | |||
SslSettings | TLS/SSL options, including client certificates, revocation handling, and enabled and disabled TLS/SSL protocols. If
an exception. Data Type: SslSettings Default: Connection URI Example: | |||
UseTls | Specifies whether to require TLS for connections to the server. If you use a scheme of this option defaults to Data Type: Default: Connection URI Example: | |||
WaitQueueTimeout | The length of time the driver tries to check out a connection from a server's connection pool before timing out. Data Type: Default: 2 minutes Connection URI Example: | |||
WriteConcern | The default write-concern settings, including write timeout and journaling, for the client. See write concern for more information. Data Type: WriteConcern Default: Connection URI Example: | |||
WriteEncoding | Specifies whether UTF-8 string serialization is strict or lenient. With strict encoding, the driver will throw an exception when it encounters an invalid UTF-8 byte sequence. Data Type: Default: Strict encoding Connection URI Example: N/A |
2.简单使用
命令 | 语法 | |||||||||
---|---|---|---|---|---|---|---|---|---|---|
Find a Document |
输出
| |||||||||
Find a Document (Async) |
输出
| |||||||||
Find Multiple Documents |
输出
| |||||||||
Find Multiple Documents (Async) |
输出
| |||||||||
Insert a Document |
| |||||||||
Insert a Document (Async) |
| |||||||||
Insert Multiple Documents |
| |||||||||
Insert Multiple Documents (Async) |
| |||||||||
Update a Document |
| |||||||||
Update a Document (Async) |
| |||||||||
Update Multiple Documents |
| |||||||||
Update Multiple Documents (Async) |
| |||||||||
Update an Array in a Document |
| |||||||||
Replace a Document |
| |||||||||
Replace a Document (Async) |
| |||||||||
Delete a Document |
| |||||||||
Delete a Document (Async) |
| |||||||||
Delete Multiple Documents |
| |||||||||
Delete Multiple Documents (Async) |
| |||||||||
Access Data from a Cursor Iteratively |
输出
| |||||||||
Count Documents |
输出
| |||||||||
List the Distinct Documents or Field Values |
输出
| |||||||||
Limit the Number of Documents Retrieved |
输出
| |||||||||
Skip Retrieved Documents |
输出
| |||||||||
Sort the Documents When Retrieving Them |
输出
| |||||||||
Project Document Fields When Retrieving Them |
输出
| |||||||||
Create an Index |
|
参考资料: