pymongo(三)-更新数据

93 阅读1分钟
# coding=utf-8

import pymongo

# 初始化连接
client = pymongo.MongoClient(host='localhost', port=27017)

# 指定book数据库
db = client['book']

# 指定集合(类似于数据库中的表)
collection = db['biquge']

# 更新单条数据
collection.update_one({'name': '雪中悍刀行'}, {'$set': {'name': 'xzhdx'}})

# 更新多条数据
results = collection.update_many({'name': 'xzhdx'}, {'$set': {'name': '雪中悍刀行'}})

# 条件更新
condition = {'age': {'$gt': 20}}
results = collection.update_one(condition, {'$inc': {'age': 1}})

print(results.matched_count, results.modified_count)  # matched_count: 匹配的数据条数, modified_count: 影响的数据条数