📅  最后修改于: 2023-12-03 15:03:01.371000             🧑  作者: Mango
在本篇文章中,我们将了解如何使用 Python 和 pymongo 库向 MongoDB 数据库插入和更新数据。
Python 和 pymongo 库提供了多种方法向 MongoDB 数据库插入数据,下面列出了其中两种常用方法:
insert_one()
方法插入一条数据:
import pymongo
# 建立连接
client = pymongo.MongoClient(host="localhost", port=27017)
# 指定数据库
db = client["mydatabase"]
# 指定集合
collection = db["customers"]
# 插入一条数据
data = {"name": "John Doe", "address": "Highway 37"}
insert_result = collection.insert_one(data)
# 输出插入结果
print(insert_result.inserted_id)
输出:
5dc880b6a0f0c820d34b9bd8
insert_many()
方法插入多条数据:
import pymongo
# 建立连接
client = pymongo.MongoClient(host="localhost", port=27017)
# 指定数据库
db = client["mydatabase"]
# 指定集合
collection = db["customers"]
# 插入多条数据
data = [
{"name": "Amy", "address": "Apple st 652"},
{"name": "Hannah", "address": "Mountain 21"},
{"name": "Michael", "address": "Valley 345"},
{"name": "Sandy", "address": "Ocean blvd 2"},
{"name": "Betty", "address": "Green Grass 1"},
{"name": "Richard", "address": "Sky st 331"},
{"name": "Susan", "address": "One way 98"},
{"name": "Vicky", "address": "Yellow Garden 2"},
{"name": "Ben", "address": "Park Lane 38"},
{"name": "William", "address": "Central st 954"},
{"name": "Chuck", "address": "Main Road 989"},
{"name": "Viola", "address": "Sideway 1633"}
]
insert_result = collection.insert_many(data)
# 输出插入结果
print(insert_result.inserted_ids)
输出:
[ObjectId('5dc880b7a0f0c820d34b9bd9'), ObjectId('5dc880b7a0f0c820d34b9bda'), ObjectId('5dc880b7a0f0c820d34b9bdb'), ObjectId('5dc880b7a0f0c820d34b9bdc'), ObjectId('5dc880b7a0f0c820d34b9bdd'), ObjectId('5dc880b7a0f0c820d34b9bde'), ObjectId('5dc880b7a0f0c820d34b9bdf'), ObjectId('5dc880b7a0f0c820d34b9be0'), ObjectId('5dc880b7a0f0c820d34b9be1'), ObjectId('5dc880b7a0f0c820d34b9be2'), ObjectId('5dc880b7a0f0c820d34b9be3'), ObjectId('5dc880b7a0f0c820d34b9be4')]
Python 和 pymongo 库提供了两种方法更新 MongoDB 数据库中的数据,下面列出了这两种常用方法:
update_one()
方法修改一条数据:
import pymongo
# 建立连接
client = pymongo.MongoClient(host="localhost", port=27017)
# 指定数据库
db = client["mydatabase"]
# 指定集合
collection = db["customers"]
# 修改一条数据
query = {"name": "John Doe"}
new_values = {"$set": {"address": "Canyon 123"}}
update_result = collection.update_one(query, new_values)
# 输出修改结果
print(update_result.modified_count)
输出:
1
update_many()
方法修改多条数据:
import pymongo
# 建立连接
client = pymongo.MongoClient(host="localhost", port=27017)
# 指定数据库
db = client["mydatabase"]
# 指定集合
collection = db["customers"]
# 修改多条数据
query = {"address": {"$regex": "^S"}}
new_values = {"$set": {"address": "Canyon 123"}}
update_result = collection.update_many(query, new_values)
# 输出修改结果
print(update_result.modified_count)
输出:
2
在本篇文章中,我们了解了如何使用 Python 和 pymongo 库向 MongoDB 数据库插入和更新数据。使用上述的方法可以帮助我们更方便地操作 MongoDB 数据库,提高开发效率。