Flask API调用MongoDB update_one更新文档时报$运算符错误如何解决?
问题原因
你当前存在3个核心错误,也是触发报错的直接原因:
- 接口代码逻辑错误:两次调用
request.get_json()拿到的都是完整的请求体,传给update_one的查询条件和更新参数都是完整请求体,完全没有做拆分,导致第二个更新参数包含非$开头的键,触发pymongo校验报错ValueError: update only works with $ operators - 查询条件写法错误:你要匹配的是内嵌字段
0.truck_id等于"A01",不是根节点下的0字段等于{"truck_id":"A01"} - 请求体结构错误:更新字段路径写为根节点下的
month,实际要更新的是内嵌字段0.month,且没有将查询条件和更新参数做结构拆分
修复方案
1. 调整Flask接口代码
@app.route('/update', methods=["PUT"]) def updateElement(): req_data = request.get_json() # 拆分查询条件和更新内容 query_filter = req_data.get("filter") update_data = req_data.get("update") # 基础参数校验 if not query_filter or not update_data: return jsonify({"code": 400, "msg": "查询条件和更新内容不能为空"}), 400 result = SampleTable.update_one(query_filter, update_data) # 不能直接序列化update_one返回的结果对象,取对应属性返回 return jsonify({ "code": 200, "matched_count": result.matched_count, "modified_count": result.modified_count })
注意原代码中updateElement函数的缩进错误,要和@app.route装饰器对齐。
2. 调整Postman请求体内容
{ "filter": { "0.truck_id": "A01" }, "update": { "$set": { "0.month": "May" } } }
扩展优化建议
你当前用数字作为键存储卡车数据的结构灵活性很差,建议调整为数组结构:
{ "trucks": [ { "available": "no", "end_date": "10", "month": "June", "start_date": "15", "truck_id": "A01" }, { "available": "yes", "end_date": null, "month": "June", "start_date": null, "truck_id": "A02" } ] }
调整后更新任意truck_id对应的数据不需要写死数字键,查询和更新写法如下:
{ "filter": { "trucks.truck_id": "A01" }, "update": { "$set": { "trucks.$.month": "May" } } }
内容的提问来源于stack exchange,提问作者Umut K.
相关产品推荐
相关产品推荐

