Overview
在本指南中,您可以学习;了解如何使用.NET/ C#驱动程序替换MongoDB集合中的文档。
.NET/ C#驱动程序提供了 ReplaceOne()
和 ReplaceOneAsync()
方法。 这些方法删除第一个符合搜索条件的文档中的所有字段(_id
字段除外),然后将指定的字段和值插入到该文档中。
样本数据
本指南中的示例使用 sample_restaurants
数据库中的 restaurants
集合。此集合中的文档使用以下 Restaurant
、Address
和 GradeEntry
类作为模型:
public class Restaurant { public ObjectId Id { get; set; } public string Name { get; set; } [ ] public string RestaurantId { get; set; } public string Cuisine { get; set; } public Address Address { get; set; } public string Borough { get; set; } public List<GradeEntry> Grades { get; set; } }
public class Address { public string Building { get; set; } [ ] public double[] Coordinates { get; set; } public string Street { get; set; } [ ] public string ZipCode { get; set; } }
public class GradeEntry { public DateTime Date { get; set; } public string Grade { get; set; } public float? Score { get; set; } }
注意
restaurants
集合中的文档使用蛇形命名规则。本指南中的示例使用 ConventionPack
将集合中的字段反序列化为 Pascal 语句,并将它们映射到 Restaurant
类中的属性。
如需了解有关自定义序列化的更多信息,请参阅自定义序列化。
此集合来自Atlas提供的示例数据集。请参阅.NET/ C#驱动程序入门,学习;了解如何创建免费的MongoDB 集群并加载此示例数据。
替换一个文档
要替换集合中的文档,请调用 ReplaceOne()
或 ReplaceOneAsync()
方法。 这些方法接受以下参数:
Parameter | 说明 |
---|---|
| 查询过滤,用于指定要替换的文档。您可以使用 |
| 替换文档,指定要插入新文档中的字段和值。如果集合中的文档映射到C#类,则替换文档可以是该类的实例。 数据类型: |
| 可选。 数据类型: ReplaceOptions |
| 可选。可用于取消操作的令牌。 |
以下代码示例演示了如何执行替换操作。 该代码执行以下步骤:
使用
Builders
类创建查询过滤。 过滤匹配cuisine
字段具有值"Pizza"
的所有文档。创建新的
Restaurant
对象。在
restaurants
集合上调用ReplaceOne()
方法。 此操作会在集合中查找第一个匹配的文档,并将其替换为新创建的文档。
选择 Synchronous 或 Asynchronous 标签页,查看相应的代码。
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Finds the ID of the first restaurant document that matches the filter var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); var oldId = oldPizzaRestaurant.Id; // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; // Replaces the existing restaurant document with the new document return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Finds the ID of the first restaurant document that matches the filter var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); var oldId = oldPizzaRestaurant.Id; // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; // Asynchronously replaces the existing restaurant document with the new document return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);
重要
_id
字段的值不可变。如果您的替换文档指定 _id
字段的值,则它必须与现有文档的 _id
值匹配。
如果替换文档没有为 _id
字段指定值,您可以将 [BsonIgnoreIfDefault]
属性添加到普通旧 CLR/类对象 (POCO) 中的 _id
字段。 如果 POCO 中的 _id
字段属于 ObjectId
类型,请使用 [BsonIgnoreIfDefault]
。
以下示例展示了如何添加此属性:
public class Restaurant { [ ] public ObjectId Id { get; set; } // Other properties }
自定义替换操作
ReplaceOne()
和 ReplaceOneAsync()
方法可以选择接受 ReplaceOptions
对象作为参数,该对象表示可用于配置替换操作的选项。
ReplaceOptions
类包含以下属性:
属性 | 说明 | ||||
---|---|---|---|---|---|
| 指定替换操作是否绕过文档验证。这使您可以替换不满足模式验证要求的文档(如存在)。有关模式验证的更多信息,请参阅 MongoDB Server 手册。 数据类型: | ||||
| 指定对结果进行排序时要使用的语言排序规则类型。有关详细信息,请参阅本页的排序规则部分。 数据类型: 排序规则 | ||||
| 获取或设置用户提供的操作注释。有关更多信息,请参阅 MongoDB Server 手册。 数据类型: BsonValue | ||||
| 获取或设置用于扫描文档的索引。有关更多信息,请参阅 MongoDB Server 手册。 数据类型: BsonValue | ||||
| 指定如果没有文档与查询筛选条件匹配,替换操作是否执行更新或插入操作。有关更多信息,请参阅 MongoDB Server 手册。 数据类型: | ||||
| 如果查询选择了多个文档,则确定该操作替换哪个文档,因为替换操作会按指定的排序顺序替换第一个文档。要设立此选项,您必须实例化一个
数据类型: | ||||
| 获取或设置 let 文档。有关更多信息,请参阅 MongoDB Server 手册。 数据类型: BsonDocument |
以下示例执行与前一示例相同的步骤,但也使用 BypassDocumentValidation
选项绕过任何模式验证要求。 选择 Synchronous 或 Asynchronous标签页以查看相应的代码。
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Finds the ID of the first restaurant document that matches the filter var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); var oldId = oldPizzaRestaurant.Id; // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; var options = new ReplaceOptions { BypassDocumentValidation = true }; // Replaces the existing restaurant document with the new document return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant, options);
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Finds the ID of the first restaurant document that matches the filter var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); var oldId = oldPizzaRestaurant.Id; // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; var options = new ReplaceOptions { BypassDocumentValidation = true }; // Asynchronously replaces the existing restaurant document with the new document return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant, options);
排序规则
要为操作配置排序规则,请创建 Collation 类的实例。
下表描述了 Collation
构造函数接受的参数。它还列出了相应的类属性,您可以使用这些属性读取每个设置的值。
Parameter | 说明 | 类属性 |
---|---|---|
| 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 |
|
| (Optional) Specifies whether to include case comparison. When this argument is true , the driver's behavior depends on the value of
the strength argument:- If strength is CollationStrength.Primary , the driver compares base
characters and case.- If strength is CollationStrength.Secondary , the driver compares base
characters, diacritics, other secondary differences, and case.- If strength is any other value, this argument is ignored.When this argument is false , the driver doesn't include case comparison at
strength level Primary or Secondary .Data Type: boolean Default: false |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. Data Type: CollationCaseFirst Default: CollationCaseFirst.Off |
|
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: CollationStrength Default: CollationStrength.Tertiary |
|
| (Optional) Specifies whether the driver compares numeric strings as numbers. If this argument is true , the driver compares numeric strings as numbers.
For example, when comparing the strings "10" and "2", the driver treats the values
as 10 and 2, and finds 10 to be greater.If this argument is false or excluded, the driver compares numeric strings
as strings. For example, when comparing the strings "10" and "2", the driver
compares one character at a time. Because "1" is less than "2", the driver finds
"10" to be less than "2".For more information, see Collation Restrictions
in the MongoDB Server manual. Data Type: boolean Default: false |
|
| (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) |
|
| (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) |
|
| (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 |
|
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: boolean Default: false |
|
返回值
ReplaceOne()
方法返回 ReplaceOneResult
对象,ReplaceOneAsync()
方法返回 Task<ReplaceOneResult>
对象。 ReplaceOneResult
类包含以下属性:
属性 | 说明 |
---|---|
| 指示替换操作是否由 MongoDB 确认。 数据类型: |
| 指示您是否可以读取 数据类型: |
| 与查询筛选器匹配的文档数量,无论是否已有文档被替换。 数据类型: |
| 通过替换操作替换的文档数量。 数据类型: |
| 如果驱动程序执行了更新或插入,则在数据库中更新或插入的文档的 ID。 数据类型: BsonValue |
更多信息
有关替换操作的可运行示例,请参阅以下用法示例:
API 文档
要学习;了解有关此页面上使用的任何方法和类的更多信息,请参阅以下API文档: