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

UpdateMany

在本指南中,您可以学习;了解如何使用MongoDB .NET/ C#驱动程序更新多个文档中的值。

.NET/ C#驱动程序提供以下方法来更新值:

  • UpdateMany():更新多个文档中的一个或多个字段。

  • UpdateManyAsync()UpdateMany() 的异步版本。

以下部分更详细地描述了这些方法。

注意

方法重载

此页面上的许多方法都有多个重载。本指南中的示例仅显示每种方法的一个定义。有关可用重载的更多信息,请参阅API文档。

重要

输入验证

构建器类和 LINQ 查询将值传递给根本的MongoDB操作。根据设计,这些 API 不是安全清理层。在将应用程序中不受信任的输入传递给构建器或 LINQ查询之前,请对其进行验证和清理。

本指南中的示例使用 sample_restaurants 数据库中的 restaurants 集合。此集合中的文档使用以下 RestaurantAddressGradeEntry 类作为模型:

public class Restaurant
{
public ObjectId Id { get; set; }
public string Name { get; set; }
[BsonElement("restaurant_id")]
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; }
[BsonElement("coord")]
public double[] Coordinates { get; set; }
public string Street { get; set; }
[BsonElement("zipcode")]
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 类中的属性。

如需了解有关自定义序列化的更多信息,请参阅“自定义序列化”。

This collection is from the sample datasets provided by Atlas. See the Get Started with the .NET/C# Driver to learn how to create a free MongoDB cluster and load this sample data.

UpdateMany()UpdateManyAsync() 方法接受以下参数:

Parameter
说明

filter

FilterDefinition 类的实例,用于指定要更新的文档。要学习;了解如何创建查询过滤,请参阅创建查询筛选器。

数据类型: FilterDefinition

update

UpdateDefinition 类的一个实例。该对象指定更新操作的类型、要更新的字段以及每个字段的新值。要学习;了解如何创建 UpdateDefinition对象,请参阅更新多文档中的字段更新多文档中的数组

数据类型: UpdateDefinition<TDocument>

options

Optional. An instance of the UpdateOptions class that specifies the configuration for the update operation. The default value is null. For a list of available options, see Configuration Options.

数据类型: UpdateOptions

cancellationToken

可选。可用于取消操作的令牌。

数据类型CancellationToken

UpdateMany()UpdateManyAsync() 方法只接受一个 UpdateDefinition对象。 以下部分介绍如何在单个方法调用中更新多个值。

Builders.Update.Combine() 方法允许您组合多个 UpdateDefinition 对象。 此方法接受以下参数:

Parameter
说明

updates

要组合的更新定义的大量。

数据类型: UpdateDefinition<TDocument>[]

Combine() 方法返回定义多个更新操作的单个 UpdateDefinition对象。

以下代码示例使用Combine() 方法来组合 $ 设立操作和 $unset 操作:

var filter = Builders<Restaurant>.Filter
.Eq("cuisine", "Pizza");
var combinedUpdate = Builders<Restaurant>.Update.Combine(
Builders<Restaurant>.Update.Set("cuisine", "French"),
Builders<Restaurant>.Update.Unset("borough")
);
_restaurantsCollection.UpdateMany(filter, combinedUpdate);
var filter = Builders<Restaurant>.Filter
.Eq("cuisine", "Pizza");
var combinedUpdate = Builders<Restaurant>.Update.Combine(
Builders<Restaurant>.Update.Set("cuisine", "French"),
Builders<Restaurant>.Update.Unset("borough")
);
await _restaurantsCollection.UpdateManyAsync(filter, combinedUpdate);

您可以将一系列更新操作连接到单个聚合管道中。

要创建更新管道,请调用 Builders.Update.Pipeline() 方法。 此方法接受以下参数:

Parameter
说明

pipeline

代表更新管道的 PipelineDefinition实例。 要创建 PipelineDefinition对象,请为要执行的每个更新操作创建一个BSON文档,然后将这些文档传递给 PipelineDefinition.Create() 方法。

数据类型: PipelineDefinition<TDocument, TDocument>

Pipeline() 方法返回定义多个聚合阶段的单个 UpdateDefinition对象。

以下代码示例使用Pipeline() 方法来组合 $ 设立操作和 $unset 操作:

var filter = Builders<Restaurant>.Filter
.Eq("cuisine", "Pizza");
var updatePipeline = Builders<Restaurant>.Update.Pipeline(
PipelineDefinition<Restaurant, Restaurant>.Create(
new BsonDocument("$set", new BsonDocument("cuisine", "French")),
new BsonDocument("$unset", "borough")
)
);
_restaurantsCollection.UpdateMany(filter, updatePipeline);
var filter = Builders<Restaurant>.Filter
.Eq("cuisine", "Pizza");
var updatePipeline = Builders<Restaurant>.Update.Pipeline(
PipelineDefinition<Restaurant, Restaurant>.Create(
new BsonDocument("$set", new BsonDocument("cuisine", "French")),
new BsonDocument("$unset", "borough")
)
);
await _restaurantsCollection.UpdateManyAsync(filter, updatePipeline);

注意

不支持的操作

Update pipelines don't support all update operations, but they do support certain aggregation stages not found in other update definitions. For a list of update operations supported by pipelines, see Updates with Aggregation Pipeline in the MongoDB Server manual.

UpdateMany()UpdateManyAsync() 方法可以选择接受 UpdateOptions对象作为参数。 您可以使用此参数来配置更新操作。

UpdateOptions 类包含以下属性:

属性
说明

ArrayFilters

指定针对数组字段的更新操作时要修改的数组元素。有关更多信息,请参阅 MongoDB Server 手册

数据类型: IEnumerable<ArrayFilterDefinition>

BypassDocumentValidation

指定更新操作是否绕过文档验证。这使您可以更新不满足模式验证要求的文档(如存在)。有关模式验证的更多信息,请参阅 MongoDB Server 手册

数据类型: bool?

Collation

指定对结果进行排序时要使用的语言排序规则类型。有关详细信息,请参阅本页的排序规则部分。

数据类型: 排序规则

Comment

获取或设置用户提供的操作注释。有关更多信息,请参阅 MongoDB Server 手册

数据类型: BsonValue

Hint

获取或设置用于扫描文档的索引。有关更多信息,请参阅 MongoDB Server 手册

数据类型: BsonValue

IsUpsert

指定如果没有文档与查询筛选条件匹配,更新操作是否执行更新或插入操作。有关更多信息,请参阅 MongoDB Server 手册

数据类型: bool

Sort

如果查询选择了多个文档,则确定操作更新哪个文档,因为更新操作会按指定的排序顺序更新第一个文档。要设立此选项,您必须实例化一个 UpdateOptions<T>实例,该实例使用对数据进行建模的泛型类型,如以下代码所示:

var options = new UpdateOptions<Restaurant>
{
Sort = Builders<Restaurant>.Sort.Ascending(r => r.Name)
};

数据类型: SortDefinition<T>

Let

获取或设置 let 文档。有关更多信息,请参阅 MongoDB Server 手册

数据类型: BsonDocument

要为操作配置排序规则,请创建 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手册中的排序规则页面。

UpdateMany() 方法返回 UpdateResultUpdateManyAsync() 方法返回 Task<UpdateResult>对象。 UpdateResult 类包含以下属性:

属性
说明

IsAcknowledged

指示更新操作是否由 MongoDB 确认。

数据类型: bool

IsModifiedCountAvailable

指示您是否可以读取 UpdateResult 上的更新记录计数。

数据类型: bool

MatchedCount

与查询过滤匹配的文档数量,无论文档是否已更新。

数据类型: long

ModifiedCount

通过更新操作更新的文档数量。

数据类型: long

UpsertedId

如果驱动程序执行了更新或插入,则在数据库中更新或插入的文档的 ID。

数据类型: BsonValue

本页包括一个简短的交互式实验室,演示了如何使用 UpdateManyAsync() 方法修改数据。无需安装 MongoDB 或代码编辑器,即可直接在浏览器窗口中完成此实验。

要启动实验室,请单击页面顶部的 Open Interactive Tutorial 按钮。要将实验室扩展为全屏格式,请单击实验室窗格右上角的全屏按钮 ()。

有关更新操作的可运行示例,请参阅以下用法示例:

要学习;了解有关创建查询筛选器的更多信息,请参阅创建查询筛选器指南。

有关本指南中讨论的任何方法或类型的更多信息,请参阅以下API文档: