Docs 菜单

插入文档

在本指南中,您可以了解如何使用 PyMongo 通过执行插入操作将文档添加到 MongoDB 集合。

插入操作将一个或多个文档插入 MongoDB 集合。 您可以使用 insert_one()insert_many()方法执行插入操作。

注意

_id字段必须是唯一的

在MongoDB集合中,每个文档都必须包含具有唯一值的 _id字段。

如果为 _id字段指定值,则必须确保该值在集合中是唯一的。如果不指定值,驾驶员会自动为该字段生成唯一的 ObjectId 值。

我们建议让驾驶员自动生成 _id 值以确保唯一性。重复的 _id 值违反了唯一索引约束,导致驾驶员返回错误。

本指南中的示例使用 Atlas示例数据集中sample_restaurants.restaurants集合。 要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅 PyMongo入门教程。

要将单个文档添加到 MongoDB 集合,请调用insert_one()方法并传递要添加的文档。

以下示例将文档插入restaurants集合:

sample_restaurants.restaurants.insert_one({"name" : "Mongo's Burgers"})

要将多个文档添加到 MongoDB 集合,请调用insert_many()方法并传递要添加的文档列表。

以下示例将文档列表插入restaurants集合:

document_list = [
{ "name" : "Mongo's Burgers" },
{ "name" : "Mongo's Pizza" }
]
sample_restaurants.restaurants.insert_many(document_list)

insert_one()方法可以选择接受其他参数,这些参数表示可用于配置插入操作的选项。 如果不指定任何其他参数,驱动程序将不会自定义插入操作。

属性
说明

bypass_document_validation

If set to True, allows the write to opt out of document-level validation.
Defaults to False.

session

An instance of ClientSession.

comment

A comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual for more information.

insert_many()方法接受前面的可选参数以及可选的ordered属性:

属性
说明

ordered

If set to True, the driver sends documents to the server in the order provided. If an error occurs, the driver and server cancel all remaining insert operations.
Defaults to True.

以下代码使用insert_many()方法将三个新文档插入到集合中。 由于第二个方法参数为bypass_document_validation = True ,因此此插入操作会绕过文档级验证。

document_list = [
{ "name" : "Mongo's Burgers" },
{ "name" : "Mongo's Pizza" },
{ "name" : "Mongo's Tacos" }
]
sample_restaurants.restaurants.insert_many(document_list, bypass_document_validation = True)

有关使用PyMongo插入文档的可运行代码示例,请参阅将数据写入MongoDB。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: