如何让Python的MongoDB更新方法返回JSON格式结果而非游标
问题描述
我编写了一个MongoDB数据更新方法,用于修改age_upon_outcome字段的值。数据能成功更新,但方法返回的是游标对象而非JSON格式的字典。尝试用find_one(data)返回更新后的字典时,得到的却是原始数据。
测试脚本(testing_script.ipynb)
from animal_shelter import AnimalShelter # 创建实例 shelter = AnimalShelter("aacuser","Superman") data = {"age_upon_outcome":"2 years","animal_type":"Dog","breed":"Dachshund","color":"Black and tan","name":"Rhonda","outcome_subtype":"Partner","outcome_type":"Adopt","sex_upon_outcome":"Female"} new_values = {"$set": {"age_upon_outcome":"3 years"}} # 调用更新方法 shelter.update(data, new_values)
输出
<pymongo.cursor.Cursor at 0x7fb32a753f60>
类实现(animal_shelter.py)
from pymongo import MongoClient from bson.objectid import ObjectId class AnimalShelter(object): """ CRUD operations for Animal collection in MongoDB """ def __init__(self,username,password): self.client = MongoClient('mongodb://localhost:55996') self.database = self.client['AAC'] def create(self, data): if data is not None: self.database.animals.insert(data) return True else: raise Exception("Nothing to save ...") def read(self, data): return self.database.animals.find_one(data) def update(self, data, new_values): if self.database.animals.count(data): self.database.animals.update(data, new_values) return self.database.animals.find({"age_upon_outcome":"3 years"}) else: raise Exception("Nothing to update ...")
尝试过的修改(无效)
return self.database.animals.find_one(data)
期望得到更新后的字典,但返回的是原始数据。
解决方案
问题根源
- 原
update方法返回find()的结果,这是一个pymongo.cursor.Cursor对象,而非直接的字典数据。 - 使用
find_one(data)时,data包含旧的age_upon_outcome:"2 years",更新后目标文档的该字段已变为"3 years",原查询条件无法匹配到更新后的文档,因此返回旧数据或空。
修改后的update方法
场景1:更新单个文档,返回更新后的字典
def update(self, data, new_values): # 先定位目标文档 target_doc = self.database.animals.find_one(data) if target_doc: # 通过_id精准更新(避免因字段修改导致的查询失效) self.database.animals.update_one({"_id": target_doc["_id"]}, new_values) # 返回更新后的最新文档 return self.database.animals.find_one({"_id": target_doc["_id"]}) else: raise Exception("Nothing to update ...")
场景2:更新多个文档,返回所有更新后的字典列表
def update(self, data, new_values): match_count = self.database.animals.count_documents(data) if match_count > 0: # 更新所有匹配文档 self.database.animals.update_many(data, new_values) # 构建排除被修改字段的查询条件,确保能查到更新后的文档 query = {k: v for k, v in data.items() if k != "age_upon_outcome"} # 将游标转换为字典列表(可直接作为JSON格式数据返回) return list(self.database.animals.find(query)) else: raise Exception("Nothing to update ...")
测试脚本调整
调用更新方法后接收返回值并打印:
result = shelter.update(data, new_values) print(result)
关键说明
- 弃用了过时的
update方法,改用update_one/update_many,这是PyMongo官方推荐的规范用法。 - 通过
_id定位文档能避免因字段修改导致的查询失效,确保获取到更新后的最新数据。 - 将游标转换为列表(
list(find(...)))后,得到的是字典的集合,可直接作为JSON格式数据使用。
内容的提问来源于stack exchange,提问作者FireMonkey
相关产品推荐
相关产品推荐

