Overview
在本指南中,您可以学习;了解如何使用Ruby驾驶员通过执行插入操作将文档添加到MongoDB集合。
插入操作将一个或多个文档插入MongoDB集合。 您可以使用以下方法执行插入操作:
insert_one
插入单个文档insert_many
插入一个或多个文档
样本数据
本指南中的示例使用restaurants
sample_restaurants
Atlas示例数据集的 数据库中的Mongo::Client
集合。要从Ruby应用程序访问权限此集合,请创建一个连接到Atlas 集群的 对象,并将以下值分配给database
和collection
变量:
database = client.use('sample_restaurants') collection = database[:restaurants]
要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。
_id 字段
在 MongoDB 集合中,每个文档必须包含具有唯一字段值的 _id
字段。
MongoDB 允许您通过两种方式管理该字段:
自行为每个文档设置
_id
字段,确保每个值都是唯一的。让驾驶员自动为每个文档
_id
字段生成唯一的BSON::ObjectId
值。
除非您可以保证唯一性,否则我们建议让驱动程序自动生成_id
值。
注意
重复的 _id
值违反了唯一索引约束,导致驾驶员返回错误。
要了解有关_id
字段的更多信息,请参阅 MongoDB Server 手册中的唯一索引指南。
要了解有关文档结构和规则的更多信息,请参阅 MongoDB Server 手册中的文档指南。
插入一个文档
要将单个文档添加到MongoDB集合,请调用 insert_one
方法并传递要插入的文档。
以下示例将文档插入restaurants
集合:
document = { name: 'Neighborhood Bar & Grill', borough: 'Queens' } collection.insert_one(document)
插入多个文档
要将多个文档添加到MongoDB集合,请调用 insert_many
方法并传递要插入的文档列表。
以下示例将两个文档插入restaurants
集合:
documents = [ { name: 'Metropolitan Cafe', borough: 'Queens' }, { name: 'Yankee Bistro', borough: 'Bronx' } ] collection.insert_many(documents)
修改插入行为
您可以将 Hash
对象作为参数传递给 insert_one
方法,以设立配置插入操作的选项。如果不指定任何选项,驾驶员将使用默认设置执行插入操作。
下表描述了可设立配置 insert_one
操作的选项:
选项 | 说明 |
---|---|
| Instructs the driver whether to ignore document-level validation. For more information,
see Schema Validation in the MongoDB Server manual. Defaults to false . |
| Sets a comment to attach to the operation. For more information, see the insert command
fields guide in the MongoDB Server manual. |
| Sets the session to use for the operation. To learn more about sessions, see
Client Sessions and Causal Consistency Guarantees
in the MongoDB Server manual. |
| Sets the write concern for the operation. For more information, see the
Write Concern guide in the MongoDB Server manual. |
您可以通过将 Hash
作为参数传递给方法调用,对 insert_many
方法设立上述设置。您还可以使用 ordered
选项指定驾驶员将文档插入MongoDB的顺序。
例子
以下代码使用 insert_many
方法将三个新文档插入到集合中。由于已启用 bypass_document_validation
选项,因此此插入操作会绕过文档级验证。
documents = [ { name: 'Cloudy Day', borough: 'Brooklyn' }, { name: 'Squall or Shine', borough: 'Staten Island' } { name: 'Rose Field', borough: 'Queens' } ] options = { bypass_document_validation: true } collection.insert_many(documents, options)
API 文档
要进一步了解本指南所讨论的任何方法,请参阅以下 API 文档: