批量写入操作
Overview
本指南向您介绍如何使用.NET/ C#驱动程序从 MongoClient
实例执行批量写入操作。批量写入操作是对一个或多个MongoDB集合执行多个写入操作的单个数据库调用。 这比执行多个单独的写入操作更有效率,因为它减少了应用程序和数据库之间的往返次数。
样本数据
sample_restaurants.restaurants
本指南中的示例使用Atlas示例数据集中的 集合。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅快速入门教程。
定义写入操作
对于要执行的每个写入操作,请创建以下 BulkWriteModel
类之一的实例:
BulkWriteInsertOneModel<TDocument>
BulkWriteUpdateOneModel<TDocument>
BulkWriteUpdateManyModel<TDocument>
BulkWriteReplaceOneModel<TDocument>
BulkWriteDeleteOneModel<TDocument>
BulkWriteDeleteManyModel<TDocument>
以下部分介绍如何创建并使用上述类的实例,以批量写入的形式执行相应的写入操作。
提示
使用 POCO 进行批量写入操作
本指南中的示例在所有泛型类中使用 BsonDocument
类型作为 TDocument
类型。您还可以对这些类使用普通旧 CLR 对象 (POCO)。 为此,必须定义一个类来表示集合中的文档。 该类必须具有与文档中的字段匹配的属性。 有关更多信息,请参阅 POCO。
插入操作
要执行插入操作,请创建 BulkWriteInsertOneModel<TDocument>
类的实例。BulkWriteInsertOneModel<TDocument>
构造函数接受以下参数:
Parameter | 说明 |
---|---|
| The database and collection to insert the BSON document into. Data Type: string or CollectionNamespace |
| The document to insert into the collection. Data Type: TDocument |
以下示例创建了 BulkWriteInsertOneModel<TDocument>
类的实例。此实例指示驾驶员将 "name"
字段为 "Mongo's Deli"
的文档插入到 sample_restaurants.restaurants
集合中。
var insertOneModel = new BulkWriteInsertOneModel<BsonDocument>( "sample_restaurants.restaurants", new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } );
提示
插入多个文档
要插入多个文档,请为要插入的每个文档创建一个 BulkWriteInsertOneModel<TDocument>
类的实例。
更新操作
要更新单个文档,请创建 BulkWriteUpdateOneModel<TDocument>
类的实例。BulkWriteUpdateOneModel<TDocument>
构造函数接受以下参数:
Parameter | 说明 |
---|---|
| The database and collection to insert the BSON document into. Data Type: string or CollectionNamespace |
| The query filter that specifies the criteria used to match documents in your collection.
The UpdateOne operation updates only the first document that matches the
query filter.Data Type: FilterDefinition<TDocument> |
| The update operation you want to perform. For more information about update
operations, see Field Update Operators
in the MongoDB Server manual. Data Type: UpdateDefinition<TDocument> |
| Optional. The language collation to use when sorting results. See the
{+mdb+server+} manual
for more information. Data Type: Collation Default: null |
| Optional. The index to use to scan for documents.
See the MongoDB Server manual
for more information. Data Type: BsonValue Default: null |
| Optional. Specifies whether the update operation performs an upsert operation if no
documents match the query filter. See the MongoDB Server manual
for more information. Data Type: boolean Default: false |
| Specifies which array elements to modify for an update operation on an array field.
See the MongoDB Server manual
for more information. Data Type: IEnumerable<ArrayFilterDefinition> Default: null |
在以下代码示例中,BulkWriteUpdateOneModel<BsonDocument>
对象表示 sample_restaurants.restaurants
集合上的更新操作。该操作匹配集合中 name
字段的值为 "Mongo's Deli"
的第一个文档。然后,它将匹配文档中 cuisine
字段的值更新为 "Sandwiches and Salads"
。
var updateOneModel = new BulkWriteUpdateOneModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") );
要更新多个文档,请创建 BulkWriteUpdateManyModel<TDocument>
类的实例。此类的构造函数接受与 BulkWriteUpdateOneModel<TDocument>
构造函数相同的参数。BulkWriteUpdateManyModel<TDocument>
操作会更新与查询过滤匹配的所有文档。
在以下代码示例中,BulkWriteUpdateManyModel<BsonDocument>
对象表示 sample_restaurants.restaurants
集合上的更新操作。该操作匹配集合中 name
字段的值为 "Mongo's Deli"
的所有文档。然后,它将 cuisine
字段的值更新为 "Sandwiches and Salads"
。
var updateManyModel = new BulkWriteUpdateManyModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") );
替换操作
要替换文档中的字段,请创建 BulkWriteReplaceOneModel<TDocument>
类的实例。BulkWriteReplaceOneModel<TDocument>
构造函数接受以下参数:
Parameter | 说明 |
---|---|
| The database and collection to insert the BSON document into. Data Type: string or CollectionNamespace |
| The query filter that specifies the criteria used to match documents in your collection.
The UpdateOne operation updates only the first document that matches the
query filter.Data Type: FilterDefinition<TDocument> |
| The replacement document, which specifies the fields and values to insert in the
target document. Data Type: TDocument |
| Optional. The language collation to use when sorting results. See
the MongoDB Server manual
for more information. Data Type: Collation Default: null |
| Optional. The index to use to scan for documents.
See the MongoDB Server manual
for more information. Data Type: BsonValue Default: null |
| Optional. Specifies whether the update operation performs an upsert operation if no
documents match the query filter.
See the MongoDB Server manual
for more information. Data Type: boolean Default: false |
在以下示例中,BulkWriteReplaceOneModel<BsonDocument>
对象表示 sample_restaurants.restaurants
集合上的替换操作。该操作匹配集合中 restaurant_id
字段值为 "1234"
的文档。然后,它会从此文档中删除 _id
以外的所有字段,并在 name
、cuisine
、borough
和 restaurant_id
字段中设置新值。
var replaceOneModel = new BulkWriteReplaceOneModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234"), new BsonDocument{ { "name", "Mongo's Pizza" }, { "cuisine", "Pizza" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } );
提示
替换多个文档
要替换多个文档,请为每个要替换的文档创建一个 BulkWriteReplaceOneModel<TDocument>
类的实例。
删除操作
要删除文档,请创建 BulkWriteDeleteOneModel<TDocument>
类的实例。BulkWriteDeleteOneModel<TDocument>
构造函数接受以下参数:
Parameter | 说明 |
---|---|
| The database and collection to insert the BSON document into. Data Type: string or CollectionNamespace |
| The query filter that specifies the criteria used to match documents in your collection.
The DeleteOne operation deletes only the first document that matches the
query filter.Data Type: FilterDefinition<TDocument> |
| Optional. The language collation to use when sorting results. See
the MongoDB Server manual
for more information. Data Type: Collation Default: null |
| Optional. The index to use to scan for documents.
See the MongoDB Server manual
for more information. Data Type: BsonValue Default: null |
在以下代码示例中,BulkWriteDeleteOneModel<BsonDocument>
对象表示 sample_restaurants.restaurants
集合上的删除操作。该操作匹配并删除 restaurant_id
字段的值为 "5678"
的第一个文档。
var deleteOneModel = new BulkWriteDeleteOneModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678") );
要删除多个文档,请创建 BulkWriteDeleteManyModel<TDocument>
类的实例,并传递指定要删除的文档的查询过滤。DeleteMany
操作会删除与查询过滤匹配的所有文档。
在以下代码示例中,BulkWriteDeleteManyModel<BsonDocument>
对象表示 sample_restaurants.restaurants
集合上的删除操作。该操作会匹配并删除 name
字段的值为 "Mongo's Deli"
的所有文档。
var deleteManyModel = new BulkWriteDeleteManyModel<BsonDocument>( "sample_restaurants.restaurants", Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli") );
运行写入操作
为要执行的每个操作定义 BulkWriteModel
实例后,创建一个实现 IReadOnlyList
接口的类的实例。将您的 BulkWriteModel
对象添加到此 IReadOnlyList
中,然后将 IReadOnlyList
传递给 BulkWrite()
或 BulkWriteAsync()
方法。默认,这些方法按照在集合中定义的顺序运行操作。
提示
IReadOnlyList
Array
和 List
是实现IReadOnlyList
接口的两个常用类。
从以下标签页中进行选择,查看如何使用异步 BulkWriteAsync()
方法和同步 BulkWrite()
方法来执行批量写入操作。
var client = new MongoClient("mongodb://localhost:27017"); var collection = "sample_restaurants.restaurants"; var bulkWriteModels = new[] { new BulkWriteInsertOneModel<BsonDocument>( collection, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ), new BulkWriteInsertOneModel<BsonDocument>( collection, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } ), new BulkWriteUpdateManyModel<BsonDocument>( collection, Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ), new BulkWriteDeleteOneModel<BsonDocument>( collection, Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234") ) }; var results = await client.BulkWriteAsync(bulkWriteModels); Console.WriteLine("Bulk write results: " + results);
var client = new MongoClient("mongodb://localhost:27017"); var collection = "sample_restaurants.restaurants"; var bulkWriteModels = new[] { new BulkWriteInsertOneModel<BsonDocument>( collection, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ), new BulkWriteInsertOneModel<BsonDocument>( collection, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } ), new BulkWriteUpdateManyModel<BsonDocument>( collection, Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ), new BulkWriteDeleteOneModel<BsonDocument>( collection, Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234") ) }; var results = client.BulkWrite(bulkWriteModels); Console.WriteLine("Bulk write results: " + results);
前面的代码示例生成以下输出:
BulkWriteResult({'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 2, 'nUpserted': 0, 'nMatched': 2, 'nModified': 2, 'nRemoved': 1, 'upserted': []}, acknowledged=True)
自定义批量写入操作
调用 BulkWrite()
或 BulkWriteAsync()
方法时,可以传递 ClientBulkWriteOptions
类的实例。ClientBulkWriteOptions
类包含以下属性,它们表示可用于配置批量写入操作的选项:
属性 | 说明 |
---|---|
| Specifies whether the operation bypasses document-level validation. For more
information, see Schema
Validation in the MongoDB Server
manual. Defaults to false . |
| A comment to attach to the operation, in the form of a BsonValue . For
more information, see the delete command
fields guide in the
MongoDB Server manual. |
| If true , the driver performs the write operations in the order
provided. If an error occurs, the remaining operations are not
attempted.If false , the driver performs the operations in an
arbitrary order and attempts to perform all operations. If any of the write
operations in an unordered bulk write fail, the driver
reports the errors only after attempting all operations.Defaults to True . |
| A map of parameter names and values, in the form of a BsonDocument . Values
must be constant or closed
expressions that don't reference document fields. For more information,
see the let statement in the
MongoDB Server manual. |
| Specifies whether the ClientBulkWriteResult object returned by the operation
includes detailed results for each successful write operation.Defaults to false . |
| The write concern to use for the write operation, as a value from the WriteConcern
enum.Defaults to the write concern of the collection on which the operation is running. |
以下代码示例使用 ClientBulkWriteOptions
对象自定义删除操作:
返回值
BulkWrite()
和 BulkWriteAsync()
方法返回包含以下属性的 ClientBulkWriteResult
对象:
属性 | 说明 |
---|---|
| Indicates whether the server acknowledged the bulk write operation. If the
value of this property is false and you try to access any other property
of the ClientBulkWriteResult object, the driver throws an exception. |
| An IReadOnlyDictionary<int, BulkWriteDeleteResult> object containing the
results of each successful delete operation, if any. |
| The number of documents deleted, if any. |
| An IReadOnlyDictionary<int, BulkWriteInsertOneResult> object containing the
results of each successful insert operation, if any. |
| The number of documents inserted, if any. |
| The number of documents matched for an update, if applicable. |
| The number of documents modified, if any. |
| An IReadOnlyDictionary<int, BulkWriteUpdateResult> object containing the
results of each successful update operation, if any. |
| The number of documents upserted, if any. |
处理异常
如果批量写入操作中的任何操作失败, .NET/ C#驱动程序会抛出 ClientBulkWriteException
,并且不会执行任何进一步的操作。
ClientBulkWriteException
对象包含以下属性:
属性 | 说明 |
---|---|
| |
| The error message. Data Type: string |
| A dictionary of errors that occurred during the bulk write operation. Data Type: IReadOnlyDictionary<int, WriteError> |
| The results of any successful operations performed before the exception was thrown. Data Type: ClientBulkWriteResult |
| Write concern errors that occurred during execution of the bulk write operation. Data Type: IReadOnlyList<MongoWriteConcernException> |
|
更多信息
要了解如何执行单个写入操作,请参阅以下指南:
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: