插入文档
概述
在本指南中,您可以学习如何使用 MongoDB .NET/C# 驱动程序通过执行插入操作将文档添加到 MongoDB 集合。
插入操作会将一个或多个文档插入到 MongoDB 集合中。.NET/C# 驱动程序提供了以下方法来执行插入操作,每个方法都有异步和同步版本:
InsertOneAsync()
或InsertOne()
InsertManyAsync()
或InsertMany()
提示
交互式实验室
本页包含一个简短的交互式实验室,演示如何使用 InsertOneAsync()
方法插入数据。您可以直接在浏览器窗口中完成此实验室,无需安装 MongoDB 或代码编辑器。
要开始实验室,请单击页面顶部的打开交互式教程 按钮。要将实验室扩展到全屏格式,请单击实验室面板右上角的全屏按钮 (⛶)。
示例数据
本指南中的示例使用 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
将集合中的字段反序列化为帕斯卡命名法,并将它们映射到Restaurant
类的属性中。
要了解更多关于自定义序列化的信息,请参阅自定义序列化。
此集合来自Atlas提供的示例数据集。请参阅快速入门了解如何创建免费的MongoDB集群并加载此示例数据。
_id
字段
在MongoDB集合中,每个文档都必须包含一个具有唯一字段值的_id
字段。
MongoDB允许您以两种方式管理此字段
您可以自己为每个文档设置此字段,确保每个
_id
字段值都是唯一的。您可以让驱动程序为每个文档的
_id
自动生成唯一的ObjectId
值。如果您未手动设置文档的_id
字段值,驱动程序将使用ObjectId
填充该字段。
除非您能保证唯一性,否则MongoDB建议您让驱动程序自动生成_id
值。
注意
重复的_id
值违反了唯一索引约束,这会导致驱动程序从InsertOne()
返回MongoWriteException
或从InsertMany()
返回MongoBulkWriteException
。
要了解更多关于_id
字段的信息,请参阅唯一索引的服务器手册条目。
要了解更多关于文档结构和规则的信息,请参阅文档的服务器手册条目。
插入一个文档
以下代码展示了如何使用异步的 InsertOneAsync()
方法或同步的 InsertOne()
方法来插入一个文档。
await _restaurantsCollection.InsertOneAsync(document);
_restaurantsCollection.InsertOne(document);
插入多个文档
以下代码展示了如何使用异步的 InsertManyAsync()
方法或同步的 InsertMany()
方法来插入多个文档。
await _restaurantsCollection.InsertManyAsync(docs);
_restaurantsCollection.InsertMany(docs);
提示
在这些方法下查找可运行的示例,请参阅 附加信息。
修改插入行为
InsertOne()
方法接受一个参数,即要插入的文档。而 InsertMany()
方法接受一个文档的 IEnumerable
集合,例如列表或数组,作为参数。
InsertOne()
方法可选地接受一个 InsertOneOptions
类型作为附加参数,该类型表示您可以使用它来配置插入操作。如果您未指定任何 InsertOneOptions
属性,则驱动程序不会自定义插入操作。
InsertOneOptions
类型允许您通过以下属性配置选项
属性 | 描述 |
---|---|
| 获取或设置一个值,表示是否绕过文档验证。如果为 true ,则允许写入操作选择退出 文档级别验证。 |
| 获取或设置操作的注释。有关更多信息,请参阅 插入命令字段。 |
InsertMany()
方法可以可选地接受一个类型为 InsertManyOptions
的附加参数,该参数包含前面的 BypassDocumentValidation
和 Comment
属性,以及额外的 IsOrdered
属性
属性 | 描述 |
---|---|
| 获取或设置一个值,指示是否按顺序满足请求。如果 true ,驱动程序将按提供的顺序将文档发送到服务器。如果发生错误,驱动程序和服务器将中止所有剩余的插入操作。有关更多信息,请参阅有序行为。默认值: true |
示例
以下代码使用 InsertMany()
方法将五个新的 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
插入这些文档,由于 _id
值重复,驱动程序将在第三个文档处抛出 MongoBulkWriteException
,但错误生成文档之前的文档仍然被插入到您的集合中。
如果您查看您的集合,您应该能够看到以下文档
{ "_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 文档