ArrayFilters 更新多个子文档的 Pymongo 错误 [英] Pymongo error for ArrayFilters to update multiple subdocuments

查看:131
本文介绍了ArrayFilters 更新多个子文档的 Pymongo 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的查询是关于更新以数组形式存储的多个子文档.

My query is regarding update multiple subdocuments stored in array forms.

环境:我已经在我的电脑中安装了 MongoDB shell 版本 v3.6.3、python 3.6.9 和 pymongo 3.6.1.

Environment : I have installed MongoDB shell version v3.6.3, python 3.6.9, and pymongo 3.6.1 in my computer.

架构示例:

dept : { "_id" : 1, "dept_name" : "paper", "dept_projs" : 2534, "dept_city" : "Pimpri-Chinchwad",
 "emps": [
         { "salary" : 10000, "city" : "Ajmer", "_id" : 1111, "emp_name" : "Jessica Ali" } ,
         { "salary" : 12000, "city" : "Dhanbad", "_id" : 1112, "emp_name" : "Samuel Sanchez" },
         { "salary" : 8000, "city" : "Gwalior", "_id" : 1113, "emp_name" : "Willie Little" } ,
        ...
          ]
}

查询:我想更新存储在数组中的选定的多个子文档.当我在 mongodb 单元格中编写此查询时,它可以工作.但是,Python3 显示错误.

db.dept.update({"emps._id":{"$gte":1111,"$lte":1114}},{"$inc":{"emps.$[idx].salary" : 20000}},{"arrayFilters":[{"idx._id":{"$gte":1111, "$lte":1114}}],multi:true})

错误:"TypeError: upsert must be True or False"

用于 Python 代码**结果

for Python code **result

E=db.dept.update({"emps._id":{"$gte":1111,"$lte":1114}},{"$inc":{"emps.$[idx].salary" :20000}},{"arrayFilters":[{"emps._id":{"$gte":1111,"$lte":1114}}],"multi":True})**

错误:pymongo.errors.OperationFailure:BSON 字段'update.updates.multi' 是错误的类型'object',预期类型'bool'

对于python代码**结果

for python code **result

E=db.dept.update({"emps._id":{"$gte":1111,"$lte":1114}},{"$inc":{"emps.$[idx].salary" : 20000}},False, True,{"arrayFilters":[{"emps._id":{"$gte":1111,"$lte":1114}}]})**

推荐答案

如果你查看 pymongo 的源代码,你会发现 update 函数不会't 接收任何关于 arrayFilters 的参数,所以你必须使用 update_one,它会接受一个名为 array_filters 的可选参数:

If you look into the source code of pymongo, you will find that the update function won't receive any parameter about arrayFilters, so you have to use update_one, which would accept a optional parameter named array_filters:

db.dept.update_one(
    {"emps._id" : {"$gte" : 1111, "$lte" : 1114}},
    {"$inc" : {"emps.$[idx].salary" : 20000}}, 
    upsert=True,
    array_filters=[{"idx._id" : {"$gte" : 1111,  "$lte"  : 1114}}]
)

这篇关于ArrayFilters 更新多个子文档的 Pymongo 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆