Overview
在本指南中,您可以了解如何使用 MongoDB .NET/C# 驱动程序通过执行插入操作将文档添加到 MongoDB 集合。
插入操作将一个或多个文档插入MongoDB集合。.NET/ C#驱动程序提供了以下方法来执行插入操作,每种方法都有同步和异步版本:
InsertOne() or ``InsertOneAsync()InsertMany()orInsertManyAsync()
提示
互动实验室
本页包括一个简短的交互式实验室,演示了如何使用 InsertOneAsync() 方法插入数据。无需安装 MongoDB 或代码编辑器,即可直接在浏览器窗口中完成此实验。
要启动实验室,请单击页面顶部的 Open Interactive Tutorial 按钮。要将实验室扩展为全屏格式,请单击实验室窗格右上角的全屏按钮 (⛶)。
样本数据
本指南中的示例使用 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 集群并加载此示例数据。
_id 字段
在 MongoDB 集合中,每个文档必须包含具有唯一字段值的 _id 字段。
MongoDB 允许您通过两种方式管理该字段:
您可以自行为每个文档设置此字段,确保每个
_id字段的值都是唯一的。您可以让驱动程序为每个文档
_id自动生成唯一的ObjectId值。如果您没有为文档手动设置_id字段值,则驱动程序将用ObjectId填充该字段。
除非您可以保证唯一性,否则 MongoDB 建议让驱动程序自动生成 _id 值。
注意
重复的 _id 值违反了唯一索引约束条件,会导致驱动程序从 InsertOne() 返回 MongoWriteException,或从 InsertMany() 返回 MongoBulkWriteException。
如要了解有关 _id 字段的更多信息,请参阅有关唯一索引的 Server 手册条目。
要了解有关文档结构和规则的更多信息,请参阅服务器手册中有关文档的条目。
插入一个文档
以下代码演示如何使用同步 InsertOne() 方法或异步 InsertOneAsync() 方法插入一个文档。
_restaurantsCollection.InsertOne(document);
await _restaurantsCollection.InsertOneAsync(document);
插入多个文档
以下代码演示如何使用同步 InsertMany() 方法或异步 InsertManyAsync() 方法插入多个文档。
_restaurantsCollection.InsertMany(docs);
await _restaurantsCollection.InsertManyAsync(docs);
提示
在附加信息下方,使用这些方法查找可运行的示例。
修改插入行为
InsertOne() 方法将您要插入的文档作为参数。InsertMany()方法采用 IEnumerable 文档集合(例如列表或数组)作为参数。
InsertOne() 方法可以选择性地采用 InsertOneOptions 类型作为附加参数,此参数表示可用来配置插入操作的选项。如果您不指定任何 InsertOneOptions 属性,驱动程序将不会自定义插入操作。
InsertOneOptions 类型允许您使用以下属性配置选项:
属性 | 说明 |
|---|---|
| 获取或设置一个值,该值指示是否绕过文档验证。 如果 |
| 获取或设置操作的注释。有关详情,请参阅插入命令字段。 |
InsertMany() 方法可以选择采用 InsertManyOptions 类型作为附加参数,该参数具有前面的 BypassDocumentValidation 和 Comment 属性,以及附加的 IsOrdered 属性:
属性 | 说明 |
|---|---|
| 获取或设置一个值,该值表示请求是否按顺序完成。如果为 默认: |
例子
以下代码使用InsertMany() 方法将五个新的文档插入到collection中,并将Restaurant BypassDocumentValidation设置为true :
// Generates 5 new restaurants by using a helper method var restaurants = GenerateDocuments(); // Creates an option object to bypass documentation validation on the documents var options = new InsertManyOptions() { BypassDocumentValidation = true }; // Inserts the new documents into the restaurants collection with the specified options _restaurantsCollection.InsertMany(restaurants, options);
InsertMany() 方法没有返回值。您可以通过对集合执行 Find() 操作来验证文档是否已成功插入。有关如何查找文档的示例,请参阅检索数据。
指定有序行为
假设要插入以下文档:
{ "_id" : 1, "name" : "Restaurant A" } { "_id" : 2, "name" : "Restaurant B" } { "_id" : 1, "name" : "Restaurant C" } { "_id" : 3, "name" : "Restaurant D" }
如果尝试使用默认InsertManyOptions 插入这些文档,则驱动程序会在插入第三个文档时抛出 MongoBulkWriteException,因为 _id 值重复。该操作仅将前两个文档添加到集合:
{ "_id" : 1, "name" : "Restaurant A" } { "_id" : 2, "name" : "Restaurant B" }
如果您在插入操作中将 IsOrdered设立为 false,则即使某些文档产生错误,驱动程序也会继续插入文档。通过此修改后的插入行为,驱动程序会引发异常,但会插入所有不会产生错误的文档:
{ "_id" : 1, "name" : "Restaurant A" } { "_id" : 2, "name" : "Restaurant B" } { "_id" : 3, "name" : "Restaurant D" }
更多信息
有关插入操作的可运行示例,请参阅以下使用示例:
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: