对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

批量写入操作

在本指南中,您可以学习;了解如何使用批量写入操作在单个数据库调用中执行多个写入操作。

考虑这样一个场景:您要插入一个文档,更新多个其他文档,然后删除一个文档。 如果使用单独的方法,则每个操作都需要调用自己的数据库。

通过使用批量写入操作,您可以通过更少的数据库调用来执行多个写入操作。 您可以在以下级别执行批量写入操作:

  • Collection: You can use the IMongoCollection.BulkWrite() or IMongoCollection.BulkWriteAsync() method to perform bulk write operations on a single collection. These methods make a database call for each type of write operation. For example, the methods perform multiple update operations in one call, but make two separate calls to the database for an insert operation and a replace operation.

  • 客户端:如果您的应用程序连接到MongoDB8 Server.0 或更高版本,则可以使用IMongoClient.BulkWrite()IMongoClient.BulkWriteAsync() 方法对同一集群中的多个集合和数据库执行批量写入操作。此方法在一次数据库调用中执行所有写入操作。

The examples in this guide use the sample_restaurants.restaurants and sample_mflix.movies collections from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.

提示

使用 POCO 进行批量写入操作

本指南中的示例在所有泛型类中使用 BsonDocument 类型作为 TDocument 类型。您还可以对这些类使用普通旧 CLR 对象 (POCO)。 为此,必须定义一个类来表示集合中的文档。 该类必须具有与文档中的字段匹配的属性。 有关更多信息,请参阅 POCO。

批量写入操作包含一个或多个写入操作。对于要执行的每个写入操作,请创建以下 WriteModel<TDocument> 类之一的实例:

  • DeleteManyModel<TDocument>

  • DeleteOneModel<TDocument>

  • InsertOneModel<TDocument>

  • ReplaceOneModel<TDocument>

  • UpdateManyModel<TDocument>

  • UpdateOneModel<TDocument>

The following sections show how to create and use instances of the preceding classes to perform the corresponding write operation in a bulk write operation. The Perform the Bulk Operation section demonstrates how to pass a list of models to the BulkWrite() or BulkWriteAsync() method to perform the bulk operation.

要执行插入操作,请创建一个InsertOneModel<TDocument>实例并指定要插入的文档。

以下示例创建了 InsertOneModel<BsonDocument> 类的实例。此实例指示驱动程序将 "name"字段为 "Mongo's Deli" 的文档插入到 restaurants集合中。

var insertOneModel = new InsertOneModel<BsonDocument>(
new BsonDocument{
{ "name", "Mongo's Deli" },
{ "cuisine", "Sandwiches" },
{ "borough", "Manhattan" },
{ "restaurant_id", "1234" }
}
);

要插入多个文档,请为每个文档创建一个InsertOneModel<TDocument>实例。

重要

重复键错误

执行批量操作时,InsertOneModel<TDocument> 无法插入集合中已存在的具有 _id 的文档。在这种情况下,驱动程序会抛出 MongoBulkWriteException

要更新单个文档,请创建 UpdateOneModel<TDocument> 的实例并传递以下参数:

  • 查询过滤,指定用于匹配集合中文档的条件。要学习;了解有关指定查询的更多信息,请参阅MongoDB Server手册中的查询和投影操作符

  • 描述要执行的更新的更新文档。要学习;了解有关指定更新的更多信息,请参阅MongoDB Server手册中的 Update Operators

UpdateOneModel<TDocument>实例指定与查询过滤匹配的第一个文档的更新。

在以下代码示例中,UpdateOneModel<BsonDocument>对象表示 restaurants集合上的更新操作。该操作匹配集合中 name字段的值为 "Mongo's Deli" 的第一个文档。然后,它将匹配文档中 cuisine字段的值更新为 "Sandwiches and Salads"

var updateOneModel = new UpdateOneModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"),
Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads")
);

要更新多个文档,请创建UpdateManyModel<TDocument>的实例并传递与UpdateOneModel<TDocument>相同的参数。 UpdateManyModel<TDocument>类指定与查询过滤匹配的所有文档的更新。

在以下代码示例中,UpdateManyModel<BsonDocument>对象表示 restaurants集合上的更新操作。该操作匹配集合中 name字段的值为 "Mongo's Deli" 的所有文档。然后,它将 cuisine字段的值更新为 "Sandwiches and Salads"

var updateManyModel = new UpdateManyModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"),
Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads")
);

替换操作会删除指定文档的所有字段和值,并将其替换为您指定的新字段和值。 要执行替换操作,请创建ReplaceOneModel<TDocument>实例并传递查询过滤以及要用于替换匹配文档的字段和值。

在以下示例中,ReplaceOneModel<BsonDocument>对象表示 restaurants集合上的替换操作。该操作匹配集合中 restaurant_id字段值为 "1234" 的文档。然后,它会从此文档中删除 _id 以外的所有字段,并在 namecuisineboroughrestaurant_id 字段中设置新值。

var replaceOneModel = new ReplaceOneModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234"),
new BsonDocument{
{ "name", "Mongo's Pizza" },
{ "cuisine", "Pizza" },
{ "borough", "Brooklyn" },
{ "restaurant_id", "5678" }
}
);

要替换多个文档,必须为每个文档创建一个ReplaceOneModel<TDocument>实例。

要删除文档,请创建DeleteOneModel<TDocument>的实例并传递查询过滤,指定要删除的文档。 DeleteOneModel<TDocument>实例提供了仅删除与查询过滤匹配的第一个文档的说明。

在以下代码示例中,DeleteOneModel<BsonDocument>对象表示 restaurants集合上的删除操作。该操作匹配并删除 restaurant_id字段的值为 "5678" 的第一个文档。

var deleteOneModel = new DeleteOneModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678")
);

要删除多个文档,请创建 DeleteManyModel<TDocument> 的实例并传递查询过滤,指定要删除的文档。DeleteManyModel<TDocument> 的实例提供了删除与查询过滤匹配的所有文档的说明。

在以下代码示例中,DeleteManyModel<BsonDocument>对象表示 restaurants集合上的删除操作。该操作会匹配并删除 name字段的值为 "Mongo's Deli" 的所有文档。

var deleteManyModel = new DeleteManyModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli")
);

为要执行的每个操作定义 WriteModel实例后,创建一个实现 IEnumerable 接口的类的实例。将您的 WriteModel 对象添加到此 IEnumerable,然后将 IEnumerable 传递给 BulkWrite()BulkWriteAsync() 方法。默认下,这些方法按照列表中定义的顺序运行操作。

提示

IEnumerable

ArrayList 是实现IEnumerable 接口的两个常用类。

从以下标签页中进行选择,查看如何使用同步 BulkWrite() 方法和异步 BulkWriteAsync() 方法对 restaurants集合执行批量写入操作:

var models = new List<WriteModel<BsonDocument>>
{
new InsertOneModel<BsonDocument>(
new BsonDocument{
{ "name", "Mongo's Deli" },
{ "cuisine", "Sandwiches" },
{ "borough", "Manhattan" },
{ "restaurant_id", "1234" }
}
),
new InsertOneModel<BsonDocument>(
new BsonDocument{
{ "name", "Mongo's Deli" },
{ "cuisine", "Sandwiches" },
{ "borough", "Brooklyn" },
{ "restaurant_id", "5678" }
}
),
new UpdateManyModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"),
Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads")
),
new DeleteOneModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234")
)
};
var results = collection.BulkWrite(models);
Console.WriteLine(results);
var models = new List<WriteModel<BsonDocument>>
{
new InsertOneModel<BsonDocument>(
new BsonDocument{
{ "name", "Mongo's Deli" },
{ "cuisine", "Sandwiches" },
{ "borough", "Manhattan" },
{ "restaurant_id", "1234" }
}
),
new InsertOneModel<BsonDocument>(
new BsonDocument{
{ "name", "Mongo's Deli" },
{ "cuisine", "Sandwiches" },
{ "borough", "Brooklyn" },
{ "restaurant_id", "5678" }
}
),
new UpdateManyModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"),
Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads")
),
new DeleteOneModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234")
)
};
var results = await collection.BulkWriteAsync(models);
Console.WriteLine(results);

前面的代码示例生成以下输出:

MongoDB.Driver.BulkWriteResult1+Acknowledged[MongoDB.Bson.BsonDocument]

注意

当驱动程序运行批量操作时,它会使用目标集合的写关注(write concern)。无论执行顺序如何,驱动程序在尝试所有操作后都会报告所有写关注(write concern)错误。

调用 BulkWrite()BulkWriteAsync() 方法时,可以传递 BulkWriteOptions 类的实例。BulkWriteOptions 类包含以下属性,它们表示可用于配置批量写入操作的选项:

属性
说明

BypassDocumentValidation

Specifies whether the operation bypasses document-level validation. For more information, see Schema Validation in the MongoDB Server manual.
Defaults to False.

Comment

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.

IsOrdered

如果 True,则驱动程序会按照提供的顺序执行写入操作。如果发生错误,则不会尝试其他操作。

如果 False,驱动程序以任意顺序执行操作,并尝试执行所有操作。如果无序批量写入中的任何写入操作失败,驱动程序仅在尝试所有操作后报告错误。
默认为 True

Let

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.

以下代码示例使用 BulkWriteOptions对象执行无序批量写入操作:

var models = new List<WriteModel<BsonDocument>>
{
new DeleteOneModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678")
)
};
var options = new BulkWriteOptions
{
IsOrdered = false,
};
collection.BulkWrite(models, options);
var models = new List<WriteModel<BsonDocument>>
{
new DeleteOneModel<BsonDocument>(
Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678")
)
};
var options = new BulkWriteOptions
{
IsOrdered = false,
};
await collection.BulkWriteAsync(models, options);

BulkWrite()BulkWriteAsync() 方法返回包含以下属性的 BulkWriteResult对象:

属性
说明

IsAcknowledged

指示服务器是否确认了批量写入操作。如果此属性的值为 False,并且您尝试访问 BulkWriteResult 对象的任何其他属性,则驱动程序会抛出异常。

DeletedCount

删除的文档数量(如有)。

InsertedCount

插入的文档数量(如有)。

MatchedCount

更新匹配的文档数(如有)。

ModifiedCount

已修改文档的数量(如有)。

IsModifiedCountAvailable

指示修改后的计数是否可用。

Upserts

包含有关导致更新或插入(upsert)操作的每个请求的信息的列表。

RequestCount

批处理操作中的请求数。

如果批量写入操作中的任何操作失败, .NET/ C#驱动程序会抛出 BulkWriteError,并且不会执行任何进一步的操作。

BulkWriteError对象包含 Index属性,该属性描述导致错误的请求的索引。

连接到运行MongoDB Server 8.0 或更高版本的部署时,可以使用 IMongoClient.BulkWrite()IMongoClient.BulkWriteAsync() 方法写入同一集群中的多个数据库和集合。这些方法在一次调用中执行所有写入操作。

对于要执行的每个写入操作,请创建以下 BulkWriteModel 类之一的实例:

  • BulkWriteInsertOneModel<TDocument>

  • BulkWriteUpdateOneModel<TDocument>

  • BulkWriteUpdateManyModel<TDocument>

  • BulkWriteReplaceOneModel<TDocument>

  • BulkWriteDeleteOneModel<TDocument>

  • BulkWriteDeleteManyModel<TDocument>

The following sections show how to create and use instances of the preceding classes to perform the corresponding write operation in a bulk write. The Perform the Bulk Operation section demonstrates how to pass a list of models to the BulkWrite() or BulkWriteAsync() method to perform the bulk operation.

要执行插入操作,请创建 BulkWriteInsertOneModel<TDocument> 类的实例。BulkWriteInsertOneModel<TDocument> 构造函数接受以下参数:

Parameter
说明

collectionNamespace

The database and collection to insert the BSON document into.

Data Type: string or CollectionNamespace

document

要插入集合的文档。

数据类型: TDocument

以下示例创建 BulkWriteInsertOneModel<TDocument> 类的实例。这些实例指示驱动程序将文档插入到 sample_restaurants.restaurantssample_mflix.movies 集合中。

var restaurantToInsert = new BulkWriteInsertOneModel<BsonDocument>(
"sample_restaurants.restaurants",
new BsonDocument{
{ "name", "Mongo's Deli" },
{ "cuisine", "Sandwiches" },
{ "borough", "Manhattan" },
{ "restaurant_id", "1234" }
}
);
var movieToInsert = new BulkWriteInsertOneModel<BsonDocument>(
"sample_mflix.movies",
new BsonDocument{
{ "title", "Silly Days" },
{ "year", 2022 }
}
);

要更新单个文档,请创建 BulkWriteUpdateOneModel<TDocument> 类的实例。BulkWriteUpdateOneModel<TDocument> 构造函数接受以下参数:

Parameter
说明

collectionNamespace

The database and collection to insert the BSON document into.

Data Type: string or CollectionNamespace

filter

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>

update

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>

collation

Optional. The language collation to use when sorting results. See the Collation section of this page for more information.

Data Type: Collation
Default: null

hint

Optional. The index to use to scan for documents. See the MongoDB Server manual for more information.

Data Type: BsonValue
Default: null

isUpsert

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

arrayFilters

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.restaurantssample_mflix.movies 集合的更新操作。

var restaurantUpdate = new BulkWriteUpdateOneModel<BsonDocument>(
"sample_restaurants.restaurants",
Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"),
Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads")
);
var movieUpdate = new BulkWriteUpdateOneModel<BsonDocument>(
"sample_mflix.movies",
Builders<BsonDocument>.Filter.Eq("title", "Carrie"),
Builders<BsonDocument>.Update.Set("seen", True)
);

要更新多个文档,请创建 BulkWriteUpdateManyModel<TDocument> 类的实例。此类的构造函数接受与 BulkWriteUpdateOneModel<TDocument> 构造函数相同的参数。BulkWriteUpdateManyModel<TDocument>操作会更新与查询过滤匹配的所有文档。

在以下代码示例中,BulkWriteUpdateManyModel<BsonDocument>对象表示 sample_restaurants.restaurants集合上的更新操作。该操作匹配集合中 name字段的值为 "Starbucks" 的所有文档。然后,它将 cuisine字段的值更新为 "Coffee (Chain)"

var updateManyModel = new BulkWriteUpdateManyModel<BsonDocument>(
"sample_restaurants.restaurants",
Builders<BsonDocument>.Filter.Eq("name", "Starbucks"),
Builders<BsonDocument>.Update.Set("cuisine", "Coffee (Chain)")
);

要替换文档中的字段,请创建 BulkWriteReplaceOneModel<TDocument> 类的实例。BulkWriteReplaceOneModel<TDocument> 构造函数接受以下参数:

Parameter
说明

collectionNamespace

The database and collection to insert the BSON document into.

Data Type: string or CollectionNamespace

filter

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>

replacement

替换文档,用于指定要插入目标文档的字段和值。

数据类型: TDocument

collation

Optional. The language collation to use when sorting results. See the Collation section of this page for more information.

Data Type: Collation
Default: null

hint

Optional. The index to use to scan for documents. See the MongoDB Server manual for more information.

Data Type: BsonValue
Default: null

isUpsert

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.restaurantssample_mflix.movies 集合的替换操作。

var restaurantReplacement = 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" }
}
);
var movieReplacement = new BulkWriteReplaceOneModel<BsonDocument>(
"sample_mflix.movies",
Builders<BsonDocument>.Filter.Eq("title", "Insomnia"),
new BsonDocument{
{ "name", "Loving Sylvie" },
{ "year", 1999 }
}
);

要删除文档,请创建 BulkWriteDeleteOneModel<TDocument> 类的实例。BulkWriteDeleteOneModel<TDocument> 构造函数接受以下参数:

Parameter
说明

collectionNamespace

The database and collection to insert the BSON document into.

Data Type: string or CollectionNamespace

filter

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>

collation

Optional. The language collation to use when sorting results. See the Collation section of this page for more information.

Data Type: Collation
Default: null

hint

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.restaurantssample_mflix.movies 集合删除操作。

var restaurantToDelete = new BulkWriteDeleteOneModel<BsonDocument>(
"sample_restaurants.restaurants",
Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678")
);
var movieToDelete = new BulkWriteDeleteOneModel<BsonDocument>(
"sample_mflix.movies",
Builders<BsonDocument>.Filter.Eq("title", "Mr. Nobody")
);

要删除多个文档,请创建 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

ArrayList 是实现IReadOnlyList 接口的两个常用类。

从以下标签页中进行选择,查看如何使用同步 BulkWrite() 方法和异步 BulkWriteAsync() 方法对多个命名空间执行批量写入操作。

var client = new MongoClient("mongodb://localhost:27017");
var restaurantNamespace = "sample_restaurants.restaurants";
var movieNamespace = "sample_mflix.movies";
var bulkWriteModels = new[]
{
new BulkWriteInsertOneModel<BsonDocument>(
restaurantNamespace,
new BsonDocument{
{ "name", "Mongo's Deli" },
{ "cuisine", "Sandwiches" },
{ "borough", "Manhattan" },
{ "restaurant_id", "1234" }
}
),
new BulkWriteInsertOneModel<BsonDocument>(
movieNamespace,
new BsonDocument{
{ "name", "Sarah's Secret" },
{ "year", 1988 }
}
),
new BulkWriteUpdateManyModel<BsonDocument>(
restaurantNamespace,
Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"),
Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads")
),
new BulkWriteDeleteOneModel<BsonDocument>(
movieNamespace,
Builders<BsonDocument>.Filter.Eq("title", "House")
)
};
var result = client.BulkWrite(bulkWriteModels);
Console.WriteLine(result);
var client = new MongoClient("mongodb://localhost:27017");
var restaurantNamespace = "sample_restaurants.restaurants";
var movieNamespace = "sample_mflix.movies";
var bulkWriteModels = new[]
{
new BulkWriteInsertOneModel<BsonDocument>(
restaurantNamespace,
new BsonDocument{
{ "name", "Mongo's Deli" },
{ "cuisine", "Sandwiches" },
{ "borough", "Manhattan" },
{ "restaurant_id", "1234" }
}
),
new BulkWriteInsertOneModel<BsonDocument>(
movieNamespace,
new BsonDocument{
{ "name", "Sarah's Secret" },
{ "year", 1988 }
}
),
new BulkWriteUpdateManyModel<BsonDocument>(
restaurantNamespace,
Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"),
Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads")
),
new BulkWriteDeleteOneModel<BsonDocument>(
movieNamespace,
Builders<BsonDocument>.Filter.Eq("title", "House")
)
};
var result = await client.BulkWriteAsync(bulkWriteModels);
Console.WriteLine(result);

前面的代码示例生成以下输出:

BulkWriteResult({'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 2, 'nUpserted': 0, 'nMatched': 2, 'nModified': 2, 'nRemoved': 1, 'upserted': []}, acknowledged=True)

调用 BulkWrite()BulkWriteAsync() 方法时,可以传递 ClientBulkWriteOptions 类的实例。ClientBulkWriteOptions 类包含以下属性,它们表示可用于配置批量写入操作的选项:

属性
说明

BypassDocumentValidation

Specifies whether the operation bypasses document-level validation. For more information, see Schema Validation in the MongoDB Server manual.
Defaults to false.

Comment

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.

IsOrdered

如果 true,则驱动程序会按照提供的顺序执行写入操作。如果发生错误,则不会尝试其他操作。

如果 false,驱动程序以任意顺序执行操作,并尝试执行所有操作。如果无序批量写入中的任何写入操作失败,驱动程序仅在尝试所有操作后报告错误。
默认为 True

Let

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.

VerboseResult

指定操作返回的 ClientBulkWriteResult 对象是否包含每个成功写入操作的详细结果。
默认为 false

WriteConcern

用于写入操作的写关注(write concern),作为 WriteConcern 枚举中的一个值。
默认为操作所在集合的写关注(write concern)。

以下代码示例使用 ClientBulkWriteOptions对象自定义批量写入操作:

var client = new MongoClient("mongodb://localhost:27017");
var deleteOneModel = new BulkWriteDeleteOneModel<BsonDocument>(
"sample_restaurants.restaurants",
Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678")
);
var clientBulkWriteOptions = new ClientBulkWriteOptions
{
IsOrdered = false,
WriteConcern = WriteConcern.Unacknowledged,
VerboseResult = true
};
var result = client.BulkWrite(deleteOneModel, clientBulkWriteOptions);
var client = new MongoClient("mongodb://localhost:27017");
var deleteOneModel = new BulkWriteDeleteOneModel<BsonDocument>(
"sample_restaurants.restaurants",
Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678")
);
var clientBulkWriteOptions = new ClientBulkWriteOptions
{
IsOrdered = false,
WriteConcern = WriteConcern.Unacknowledged,
VerboseResult = true
};
var result = await client.BulkWriteAsync(deleteOneModel, clientBulkWriteOptions);

BulkWrite()BulkWriteAsync() 方法返回包含以下属性的 ClientBulkWriteResult对象:

属性
说明

Acknowledged

指示服务器是否确认了批量写入操作。如果此属性的值为 false,并且您尝试访问 ClientBulkWriteResult 对象的任何其他属性,则驱动程序会抛出异常。

DeleteResults

包含每个成功删除操作的结果(如果有)的 IReadOnlyDictionary<int, BulkWriteDeleteResult>对象。

DeletedCount

删除的文档数量(如有)。

InsertResults

一个包含每个成功插入操作结果(如有)的 IReadOnlyDictionary<int, BulkWriteInsertOneResult> 对象。

InsertedCount

插入的文档数量(如有)。

MatchedCount

更新匹配的文档数(如有)。

ModifiedCount

已修改文档的数量(如有)。

UpsertResults

一个包含每个成功更新操作的结果(如有)的 IReadOnlyDictionary<int, BulkWriteUpdateResult> 对象。

UpsertedCount

已更新或插入的文档数量(如有)。

如果批量写入操作中的任何操作失败, .NET/ C#驱动程序会抛出 ClientBulkWriteException,并且不会执行任何进一步的操作。

ClientBulkWriteException对象包含以下属性:

属性
说明

connectionId

The connection identifier.

Data Type: ConnectionId

message

错误消息。

数据类型: string

writeErrors

A dictionary of errors that occurred during the bulk write operation.

Data Type: IReadOnlyDictionary<int, WriteError>

partialResult

The results of any successful operations performed before the exception was thrown.

Data Type: ClientBulkWriteResult

writeConcernErrors

Write concern errors that occurred during execution of the bulk write operation.

Data Type: IReadOnlyList<MongoWriteConcernException>

innerException

The inner exception.

Data Type: Exception

要为操作配置排序规则,请创建 Collation 类的实例。

下表描述了 Collation 构造函数接受的参数。它还列出了相应的类属性,您可以使用这些属性读取每个设置的值。

Parameter
说明
类属性

locale

Specifies the International Components for Unicode (ICU) locale. For a list of supported locales, see Collation Locales and Default Parameters in the MongoDB Server Manual.

If you want to use simple binary comparison, use the Collation.Simple static property to return a Collation object with the locale set to "simple".
Data Type: string

Locale

caseLevel

(可选)指定是否包含大小写比较。

当此参数为 true 时,驱动程序的行为取决于 strength 参数的值:

- 如果 strengthCollationStrength.Primary,则驱动程序会比较基本字符和大小写。
- 如果 strengthCollationStrength.Secondary,则驱动程序会比较基本字符、变音符、其他次要差异和大小写。
- 如果 strength 为任何其他值,则会忽略此参数。

当此参数为 false 时,驱动程序不会在强度级别 PrimarySecondary 包含大小写比较。

数据类型boolean
默认值false

CaseLevel

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Data Type: CollationCaseFirst
Default: CollationCaseFirst.Off

CaseFirst

strength

(Optional) Specifies the level of comparison to perform, as defined in the ICU documentation.

Data Type: CollationStrength
Default: CollationStrength.Tertiary

Strength

numericOrdering

(可选)指定驾驶员是否将数字字符串作为数字进行比较。如果此参数为

true10210210

false102,则驾驶员将数字字符串作为数字进行比较。示例,在比较字符串1 2102"" 和和“”,则驾驶员会将这些值视为 和 ,并发现 更大。如果此参数为 或已排除,则驾驶员会将数字字符串作为字符串进行比较。示例,在比较字符串 ""

和和“”,驾驶员一次比较一个字符。因为""小于“”,则驾驶员会找到“”小于“”。有关更多信息,请参阅MongoDB Server手册中的排序规则限制。数据类型:

boolean
默认值:false

NumericOrdering

alternate

(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.

Data Type: CollationAlternate
Default: CollationAlternate.NonIgnorable (spaces and punctuation are considered base characters)

Alternate

maxVariable

(Optional) Specifies which characters the driver considers ignorable when the alternate argument is CollationAlternate.Shifted.

Data Type: CollationMaxVariable
Default: CollationMaxVariable.Punctuation (the driver ignores punctuation and spaces)

MaxVariable

normalization

(Optional) Specifies whether the driver normalizes text as needed.

Most text doesn't require normalization. For more information about normalization, see the ICU documentation.

Data Type: boolean
Default: false

Normalization

backwards

(可选)指定包含变音符号的字符串是否从字符串的后部到前部排序。

数据类型boolean
默认false

Backwards

有关排序规则的更多信息,请参阅MongoDB Server手册中的排序规则页面。

要了解如何执行单个写入操作,请参阅以下指南:

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: