MongoDB使用

1.连接方式

连接 URI

        连接 URI(也称为连接字符串)可告知驱动程序如何连接到 MongoDB 部署,以及连接后如何进行操作。(例:"mongodb://username:password@host[:port]/defaultauthdb?<options>")

标准连接字符串包括以下部分:

mongodb://

必需。将其标识为标准连接格式中字符串的前缀。

username:password@

可选。身份验证凭证。如果包含这些内容,客户端将根据 authSource 中指定的数据库对用户进行身份验证。

host[:port]

必需。运行 MongoDB 的主机和可选端口号。如果未包含端口号,则驱动程序将使用默认端口 27017

/defaultauthdb

可选。如果连接字符串包含 username:password@ 身份验证档案但未指定 authSource 选项,则要使用的身份验证数据库。如果您不包含这一内容,客户端将根据 admin 数据库对用户进行身份验证。

?<options>

可选。将连接特定选项指定为 <name>=<value> 对的查询字符串。

        要使用连接 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 true and SslSettings.CheckCertificateRevocation

is set to false, the .NET/C# Driver will throw an exception.

Data Typeboolean

Defaultfalse

Connection URI ExampletlsInsecure=true

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 Typestring

Defaultnull

Connection URI ExampleappName=yourApp

AutoEncryptionOptions

Settings for automatic client-side encryption.

Data TypeAutoEncryptionOptions

Defaultnull

Connection URI Example: N/A

ClusterConfigurator

Low-level configuration options for sockets, TLS, cluster, and others.

Data Type: Action<ClusterBuilder>

Defaultnull

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 TypeCompressorConfiguration

Defaultnull

Connection URI Examplecompressors=snappy,zstd

ConnectTimeout

The length of time the driver tries to establish a single TCP socket connection

to the server before timing out.

DataTypeTimeSpan

Default: 30 seconds

Connection URI ExampleconnectTimeoutMS=0

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

SCRAM-SHA-1 or SCRAM-SHA-256, depending on the server version. See

authentication mechanisms for available

authentication mechanisms.

Data TypeMongoCredential

Defaultnull

Connection URI Example:

 
    
mongodb://user1:password1&authMechanism=GSSAPI
&authMechanismProperties=SERVICE_NAME:other,REALM:otherrealm
&authSource=$external

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 false if you specify more than one

host name.

Data Typeboolean

Defaultfalse

Connection URI ExampledirectConnection=true

HeartbeatInterval

The interval between regular server-monitoring checks. Must be greater than or

equal to 500 milliseconds.

Data TypeTimeSpan

Default: 10 seconds

Connection URI ExampleheartbeatFrequencyMS=5000

HeartbeatTimeout

The length of time a monitoring socket can be idle before timing out.

Data TypeTimeSpan

Default: Same value as ConnectTimeout

Connection URI ExampleheartbeatTimeoutMS=5000

IPv6

Specifies whether the host address is in IPv6 format.

Data Typeboolean

Defaultfalse

Connection URI Exampleipv6=true

IsFrozen

Indicates whether the settings have been frozen. Frozen settings can't be changed.

This option is read-only.

Data Typeboolean

Defaultfalse

Connection URI Example: N/A

LinqProvider

The LINQ provider to use.

Data TypeLinqProvider

DefaultLinqProvider.V3

Connection URI Example: N/A

LoadBalanced

Specifies whether the driver is connecting to a load balancer. You can set this

property to true only if:

  • You specify just one host name.

  • You're not connecting to a replica set.

  • You're not using the SrvMaxHosts property.

  • You're not using the DirectConnection property.

Data Typeboolean

Defaultfalse

Connection URI ExampleloadBalanced=true

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 TypeTimeSpan

Default: 15 milliseconds

Connection URI ExamplelocalThresholdMS=0

LoggingSettings

The settings used for logging.

Data TypeLoggingSettings

Defaultnull

Connection URI Example: N/A

MaxConnecting

The greatest number of connections a driver's connection pool may be

establishing concurrently.

Data Typeinteger

Default2

Connection URI ExamplemaxConnecting=3

MaxConnectionIdleTime

The length of time a connection can be idle before the driver closes it.

Data TypeTimeSpan

Default: 10 minutes

Connection URI ExamplemaxIdleTimeMS=300000

MaxConnectionLifeTime

The length of time a connection can be pooled before expiring.

Data TypeTimeSpan

Default: 30 minutes

Connection URI ExamplemaxLifetimeMS=50000

MaxConnectionPoolSize

The greatest number of clients or connections the driver can create in its

connection pool. This count includes connections in use.

Data Typeinteger

Default100

Connection URI ExamplemaxPoolSize=150

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 Typeinteger

Default0

Connection URI ExampleminPoolSize=1

ReadConcern

The client's default read concern.

See read concern for more information.

Data TypeReadConcern

DefaultReadConcern.Default

Connection URI ExamplereadConcernLevel=local

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 TypeUTF8Encoding

Default: Strict encoding

Connection URI Example: N/A

ReadPreference

The client's default read-preference settings. MaxStaleness represents the

longest replication lag, in wall-clock time, that a secondary can experience and

still be eligible for server selection. Specifying -1 means no maximum.

See read preference for more information.

Data TypeReadPreference

DefaultReadPreference.Primary

Connection URI Example:

 
    
readPreference=primaryPreferred
&maxStalenessSeconds=90
&readPreferenceTags=dc:ny,rack:1

You can include the readPreferenceTags parameter in the connection URI more than once. If you do, the client treats each instance as a separate tag set. The order of the tags in the URI determines the order for read preference. You can use this parameter only if the read-preference mode is not primary.

ReplicaSetName

The name of the replica set to connect to.

Data Typestring

Defaultnull

Connection URI ExamplereplicaSet=yourReplicaSet

RetryReads

Enables retryable reads.

Data Typeboolean

Defaulttrue

Connection URI ExampleretryReads=false

RetryWrites

Enables retryable writes.

Data Typeboolean

Defaulttrue

Connection URI ExampleretryWrites=false

Scheme

Specifies whether to use the standard connection string format (MongoDB)

or the DNS seed list format (MongoDBPlusSrv).

See the MongoDB Manual for more

information about connection string formats.

If the DirectConnection property is set to true and you

try to use the DNS seed list format, the .NET/C# Driver will throw an

exception.

Data TypeConnectionStringScheme

DefaultConnectionStringScheme.MongoDB

Connection URI Examplemongodb+srv://

Server

The host and port number where MongoDB is running.

Data TypeMongoServerAddress

Defaultlocalhost:27017

Connection URI Examplemongodb://sample.host:27017

ServerApi

Allows opting into Stable API versioning. See

the MongoDB Manual for more information about

Stable API versioning.

Data TypeServerApi

Defaultnull

Connection URI Example: N/A

Servers

The cluster members where MongoDB is running.

Data Type: IEnumerable<MongoServerAddress>

Defaultlocalhost:27017

Connection URI Examplemongodb://sample.host1:27017,sample.host2:27017

ServerSelectionTimeout

The length of time the driver tries to select a server before timing out.

Data TypeTimeSpan

Default: 30 seconds

Connection URI ExampleserverSelectionTimeoutMS=15000

SocketTimeout

The length of time the driver tries to send or receive on a socket before

timing out.

Data TypeTimeSpan

Default: OS default

Connection URI ExamplesocketTimeoutMS=0

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 ConnectionStringScheme.MongoDBPlusSrv. You cannot use it when connecting

to a replica set.

Data Typeinteger

Default0

Connection URI ExamplesrvMaxHosts=3

SslSettings

TLS/SSL options, including client certificates, revocation handling, and

enabled and disabled TLS/SSL protocols.

If SslSettings.CheckCertificateRevocation is set to false and

AllowInsecureTls is set to true, the .NET/C# Driver will throw

an exception.

Data TypeSslSettings

Defaultnull

Connection URI ExampletlsDisableCertificateRevocationCheck=false

UseTls

Specifies whether to require TLS for connections to the server. If you use

a scheme of "mongodb+srv" or specify other TLS options,

this option defaults to true.

Data Typeboolean

Defaultfalse

Connection URI Exampletls=true

WaitQueueTimeout

The length of time the driver tries to check out a connection from a

server's connection pool before timing out.

Data TypeTimeSpan

Default: 2 minutes

Connection URI ExamplewaitQueueTimeoutMS=0

WriteConcern

The default write-concern settings, including write timeout and

journaling, for the client.

See write concern for more information.

Data TypeWriteConcern

DefaultWriteConcern.Acknowledged

Connection URI Examplew=majority&wTimeoutMS=0&journal=true

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 TypeUTF8Encoding

Default: Strict encoding

Connection URI Example: N/A

2.简单使用

命令

语法

Find a Document

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, "Bagels N Buns");
var restaurant = _restaurantsCollection.Find(filter).FirstOrDefault();
Console.WriteLine(restaurant);

输出

{ name : "Bagels N Buns", restaurant_id : "40363427", ... }

Find a Document (Async)

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, "Bagels N Buns");
var restaurant = await _restaurantsCollection.Find(filter).FirstOrDefaultAsync();
Console.WriteLine(restaurant);

输出

{ name : "Bagels N Buns", restaurant_id : "40363427", ... }

Find Multiple Documents

var filter = Builders<Restaurant>.Filter
.Eq(r => restaurant.Cuisine, "Pizza");
var restaurants = _restaurantsCollection.Find(filter).ToList();
Console.WriteLine(restaurants);

输出

[{ name: "Como Pizza", cuisine: "Pizza", ... },{ name: "New York Pizza Suprema", cuisine: "Pizza", ... },...]

Find Multiple Documents (Async)

var filter = Builders<Restaurant>.Filter
.Eq(r => restaurant.Cuisine, "Pizza");
var restaurants = await _restaurantsCollection.Find(filter).ToListAsync();
Console.WriteLine(restaurants);

输出

[{ name: "Como Pizza", cuisine: "Pizza", ... },{ name: "New York Pizza Suprema", cuisine: "Pizza", ... },...]

Insert a Document

var insertResult = _restaurantsCollection.InsertOne(new Restaurant { Name = "Mongo's Pizza" });

Insert a Document (Async)

var insertResult = await _restaurantsCollection.InsertOneAsync(new Restaurant { Name = "Mongo's Pizza" });

Insert Multiple Documents

_restaurantsCollection.InsertMany(new List<Restaurant>
{
  new Restaurant { Name = "Mongo's Pizza" },
  new Restaurant { Name = "Mongo Grill" }
});

Insert Multiple Documents (Async)

await _restaurantsCollection.InsertManyAsync(new List<Restaurant>
{
  new Restaurant { Name = "Mongo's Pizza" },
  new Restaurant { Name = "Mongo Grill" }
});

Update a Document

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, "Bagels N Buns");
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Name, "2 Bagels 2 Buns");
var result = _restaurantsCollection.UpdateOne(filter, update);

Update a Document (Async)

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, "Bagels N Buns");
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Name, "2 Bagels 2 Buns");
var updateResult = await _restaurantsCollection.UpdateOneAsync(filter, update);

Update Multiple Documents

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, "Pizza");
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Cuisine, "Pasta and breadsticks");
var result = _restaurantsCollection.UpdateMany(filter, update);

Update Multiple Documents (Async)

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, "Pizza");
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Cuisine, "Pasta and breadsticks");
var updateResult = await _restaurantsCollection.UpdateManyAsync(filter, update);

Update an Array in a Document

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, "Bagels N Buns");
var update = Builders<Restaurant>.Update
.Push(restaurant => restaurant.Grades, new GradeEntry
{
 Date = DateTime.Now.ToUniversalTime(),
 Grade = "A",
 Score = 10
});
var result = _restaurantsCollection.UpdateOne(filter, update);

Replace a Document

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, "Pizza");
// Find ID of first pizza restaurant
var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();
var oldId = oldPizzaRestaurant.Id;
Restaurant newPizzaRestaurant = new()
{
 Id = oldId,
 Name = "Mongo's Pizza",
 Cuisine = "Pizza",
 Address = new Address
 {
    Building = "123",
    Coordinates = [123, 456],
    Street = "Pizza St",
    ZipCode = "10003"
 },
 Borough = "Manhattan",
};
var replaceResult = _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);

Replace a Document (Async)

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, "Pizza");
// Find ID of first pizza restaurant
var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();
var oldId = oldPizzaRestaurant.Id;
Restaurant newPizzaRestaurant = new()
{
  Id = oldId,
  Name = "Mongo's Pizza",
  Cuisine = "Pizza",
  Address = new Address
  {
   Building = "123",
   Coordinates = [12.3, 45.6],
   Street = "Pizza St",
   ZipCode = "10003"
  },
  Borough = "Manhattan",
};
var replaceResult = await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);

Delete a Document

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, "Ready Penny Inn");
var deleteResult = _restaurantsCollection.DeleteOne(filter);

Delete a Document (Async)

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, "Ready Penny Inn");
var deleteResult = await _restaurantsCollection.DeleteOneAsync(filter);

Delete Multiple Documents

var filter = Builders<Restaurant>.Filter
.Regex(restaurant => restaurant.Name, "Green");
var deleteResult = _restaurantsCollection.DeleteMany(filter);

Delete Multiple Documents (Async)

var filter = Builders<Restaurant>.Filter
.Regex(restaurant => restaurant.Name, "Green");
var deleteResult = await _restaurantsCollection.DeleteManyAsync(filter);

Access Data from a Cursor Iteratively

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, "Afghan)";
var cursor = _restaurantsCollection.Find(filter).ToCursor();
while (cursor.MoveNext())
{
  foreach (var r in cursor.Current)
  {
   Console.WriteLine(r.Name);
  }
}

输出

[
Afghan Kebab House
Khyber Pass
...
]

Count Documents

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, "Pizza");
var count = _restaurantsCollection.Find(filter).CountDocuments();
Console.WriteLine(count);

输出

1163

List the Distinct Documents or Field Values

var filter = Builders<Restaurant>.Filter.Empty;
var restaurants = _restaurantsCollection
.Distinct(r => r.Cuisine, filter);
Console.WriteLine(restaurants);

输出

 
    
[ Afghan, African, American, Armenian, Asian, ... ]

Limit the Number of Documents Retrieved

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, "Asian");
var restaurants = _restaurantsCollection.Find(filter).Limit(3).ToList();
Console.WriteLine(restaurants);

输出

 
    
[{ name: "China Grill", ... },{ name: "Indo Chine", ... },{ name: "Le Colonial", ... }]

Skip Retrieved Documents

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, "Asian");
var restaurants = _restaurantsCollection.Find(filter).Skip(2).ToList();
Console.WriteLine(restaurants);

输出

 
    
[{ name: "Le Colonial", ... },{ name: "Citrus Bar & Grill", ... },{ name: "Mangez Avec Moi", ... },...]

Sort the Documents When Retrieving Them

 
    
var filter = Builders<Restaurant>.Filter.Eq(restaurant => restaurant.Cuisine, "Brazilian");
var restaurants = _restaurantsCollection.Find(filter)
.SortBy(r => r.Name).ToList();
Console.WriteLine(restaurants);

输出

[
{ name: "Barzinho", ... },
{ name: "Beco", ... },
{ name: "Beija-Flor", ... },
...
]

Project Document Fields When Retrieving Them

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, "Italian");
var projection = Builders<Restaurant>.Projection
.Include(restaurant => restaurant.Name)
.Include(restaurant => restaurant.Borough)
.Exclude(restaurant => restaurant.Id);
var restaurants = _restaurantsCollection.Find(filter).Project(projection).ToList();
Console.WriteLine(restaurants);

输出

[
{ borough : "Brooklyn", name : "Philadelphia Grille Express" }
{ borough : "Manhattan", name : "Isle Of Capri Restaurant" }
{ borough : "Manhattan", name : "Marchis Restaurant" }
...
]

Create an Index

var index = Builders<Restaurant>.IndexKeys
.Ascending(restaurant => restaurant.Cuisine);
_restaurantsCollection.Indexes
.CreateOne(new CreateIndexModel<Restaurant>(index));

参考资料:

MongBD官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值