MST
星途 面试题库

面试题:Python中使用MongoDB进行数据更新操作

假设你有一个MongoDB集合名为'users',其中每个文档代表一个用户,结构为{'name': '张三', 'age': 25, 'email': 'zhangsan@example.com'}。现在要求你使用Python的pymongo库,将所有年龄大于30岁的用户的邮箱地址更新为新的邮箱地址'new_email@example.com',请编写相应的Python代码实现。
19.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
from pymongo import MongoClient

# 连接到MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database']
users_collection = db['users']

# 更新操作
result = users_collection.update_many(
    {'age': {'$gt': 30}},
    {'$set': {'email': 'new_email@example.com'}}
)

print(f"匹配的文档数: {result.matched_count}")
print(f"修改的文档数: {result.modified_count}")

# 关闭连接
client.close()