1、单条更新

基本语法

collection.update_one(查询条件字典, {'$set': 被更新的数据字典})

实现代码

__author__ = "dengxinyan"

from pymongo import MongoClient

conn = MongoClient(host='localhost', port=27017, username=None, password=None)

database = conn['spider']
collection = database['news']

# 只更新满足条件的第一条数据
res = collection.update_one({'title': "2022年10月1日早间新闻"}, {'$set': {'title': "2022年10月1日早间新闻2"}})
print(res)

2、多条更新

基本语法

collection.update_many(查询条件字典, {'$set': 被更新的数据字典})

实现代码

__author__ = "dengxinyan"

from pymongo import MongoClient

conn = MongoClient(host='localhost', port=27017, username=None, password=None)

database = conn['spider']
collection = database['news']

# 更新满足条件的所有数据
res = collection.update_many({'title': "2022年10月1日早间新闻2"}, {'$set': {'title': "2022年10月1日早间新闻3"}})
print(res)

阅读原文

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐