Docs 菜单

替换文档

在本指南中,您可以学习;了解如何使用.NET/ C#驱动程序替换MongoDB集合中的文档。

.NET/ C#驱动程序提供了 ReplaceOne()ReplaceOneAsync() 方法。 这些方法删除第一个符合搜索条件的文档中的所有字段(_id字段除外),然后将指定的字段和值插入到该文档中。

注意

方法重载

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

本指南中的示例使用 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 类中的属性。

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

此数据集来自 Atlas 提供的示例数据集。请参阅快速入门,以了解如何创建一个免费的 MongoDB 集群并加载这些示例数据。

要替换集合中的文档,请调用 ReplaceOne()ReplaceOneAsync() 方法。 这些方法接受以下参数:

Parameter
说明

filter

查询过滤,用于指定要替换的文档。您可以使用 Builders 类创建查询过滤。 有关查询筛选器的更多信息,请参阅MongoDB Server手册。

数据类型: FilterDefinition<TDocument>

replacement

替换文档,指定要插入新文档中的字段和值。如果集合中的文档映射到C#类,则替换文档可以是该类的实例。

数据类型: TDocument

options

可选。ReplaceOptions 类的实例,用于指定替换操作的配置。 默认值为 null

数据类型: ReplaceOptions

cancellationToken

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

数据类型:CancellationToken

以下代码示例演示了如何执行替换操作。 该代码执行以下步骤:

  1. 使用 Builders 类创建查询过滤。 过滤匹配 cuisine字段具有值 "Pizza" 的所有文档。

  2. 创建新的 Restaurant对象。

  3. restaurants集合上调用 ReplaceOne() 方法。 此操作会在集合中查找第一个匹配的文档,并将其替换为新创建的文档。

选择 SynchronousAsynchronous 标签页,查看相应的代码。

// 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
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
// Other properties
}

ReplaceOne()ReplaceOneAsync() 方法可以选择接受 ReplaceOptions对象作为参数,该对象表示可用于配置替换操作的选项。

ReplaceOptions 类包含以下属性:

属性
说明

BypassDocumentValidation

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

数据类型: bool?

Collation

指定排序结果时使用的语言集合类型。有关集合的更多信息,请参阅 MongoDB Server 手册

数据类型: 排序规则

Comment

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

数据类型: BsonValue

Hint

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

数据类型: BsonValue

IsUpsert

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

数据类型: bool

Let

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

数据类型: BsonDocument

以下示例执行与前一示例相同的步骤,但也使用 BypassDocumentValidation 选项绕过任何模式验证要求。 选择 SynchronousAsynchronous标签页以查看相应的代码。

// 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);

ReplaceOne() 方法返回 ReplaceOneResult对象,ReplaceOneAsync() 方法返回 Task<ReplaceOneResult>对象。 ReplaceOneResult 类包含以下属性:

属性
说明

IsAcknowledged

指示替换操作是否由 MongoDB 确认。

数据类型: bool

IsModifiedCountAvailable

指示您是否可以读取 ReplaceOneResult 上替换记录的计数。

数据类型: bool

MatchedCount

与查询筛选器匹配的文档数量,无论是否已有文档被替换。

数据类型: long

ModifiedCount

通过替换操作替换的文档数量。

数据类型: long

UpsertedId

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

数据类型: BsonValue

要学习;了解有关此页面上使用的任何方法和类的更多信息,请参阅以下API文档: