文档菜单

文档首页开发应用程序Python 驱动程序PyMongo

将数据写入 MongoDB

本页内容

  • 概述
  • 示例应用程序
  • 插入单个
  • 插入多个
  • 更新单个
  • 更新多个
  • 替换单个
  • 删除单个
  • 删除多个
  • 批量写入

在本页中,您可以查看可复制的代码示例,展示您可以使用 PyMongo 将数据写入 MongoDB 的常用方法。

提示

要了解更多关于本页上显示的任何方法,请参阅每个部分中提供的链接。

要使用本页上的示例,请将代码示例复制到示例应用程序或您自己的应用程序中。请确保用您的 MongoDB 部署的相关值替换代码示例中的所有占位符,例如<连接字符串 URI>

您可以使用以下示例应用程序来测试本页上的代码示例。要使用示例应用程序,请执行以下步骤

  1. 确保您已安装 PyMongo。

  2. 复制以下代码并将其粘贴到新的 .py 文件中。

  3. 从本页复制代码示例并将其粘贴到文件中指定的行上。

1import pymongo
2from pymongo import MongoClient
3
4try:
5 uri = "<connection string URI>"
6 client = MongoClient(uri)
7
8 database = client["<database name>"]
9 collection = database["<collection name>"]
10
11 # start example code here
12
13 # end example code here
14
15 client.close()
16
17except Exception as e:
18 raise Exception(
19 "The following error occurred: ", e)
result = collection.insert_one({ "<field name>" : "<value>" })
print(result.acknowledged)

要了解更多关于 insert_one() 方法的信息,请参阅插入文档指南。

document_list = [
{ "<field name>" : "<value>" },
{ "<field name>" : "<value>" }
]
result = collection.insert_many(document_list)
print(result.acknowledged)

要了解更多关于 insert_many() 方法的信息,请参阅插入文档指南。

query_filter = { "<field to match>" : "<value to match>" }
update_operation = { "$set" :
{ "<field name>" : "<value>" }
}
result = collection.update_one(query_filter, update_operation)
print(result.modified_count)

要了解更多关于 update_one() 方法的信息,请参阅更新文档指南。

query_filter = { "<field to match>" : "<value to match>" }
update_operation = { "$set" :
{ "<field name>" : "<value>" }
}
result = collection.update_many(query_filter, update_operation)
print(result.modified_count)

要了解更多关于 update_many() 方法的信息,请参阅更新文档指南。

query_filter = { "<field to match>" : "<value to match>" }
replace_document = { "<new document field name>" : "<new document value>" }
result = collection.replace_one(query_filter, replace_document)
print(result.modified_count)

要了解更多关于 replace_one() 方法的信息,请参阅替换文档指南。

query_filter = { "<field to match>" : "<value to match>" }
result = collection.delete_one(query_filter)
print(result.deleted_count)

要了解更多关于 delete_one() 方法的信息,请参阅删除文档指南。

query_filter = { "<field to match>" : "<value to match>" }
result = collection.delete_many(query_filter)
print(result.deleted_count)

要了解更多关于 delete_many() 方法的信息,请参阅删除文档指南。

operations = [
pymongo.InsertOne(
{
"<field name>" : "<value>"
}
),
pymongo.UpdateMany(
{ "<field to match>" : "<value to match>" },
{ "$set" : { "<field name>" : "<value>" }},
),
pymongo.DeleteOne(
{ "<field to match>" : "<value to match>" }
),
]
result = collection.bulk_write(operations)
print(result)

要了解更多关于 bulk_write() 方法的信息,请参阅批量写入指南。

← 数据库和集合