My query is regarding update multiple subdocuments stored in array forms.
Environment : I have installed MongoDB shell version v3.6.3, python 3.6.9, and pymongo 3.6.1 in my computer.
Schema sample :
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" } ,
...
]
}
Query : I would like to update selected multiple subdocuments stored in array. When I write this query in mongodb cell, it works. But, Python3 shows me error.
db.dept.update({"emps._id":{"$gte":1111,"$lte":1114}},{"$inc":{"emps.$[idx].salary" : 20000}},{"arrayFilters":[{"idx._id":{"$gte":1111, "$lte":1114}}],multi:true})
Error: "TypeError: upsert must be True or False"
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})**
Error:pymongo.errors.OperationFailure: BSON field 'update.updates.multi' is the wrong type 'object', expected type 'bool'
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}}]})**
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}}]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With