I am using python code for updating multiple elements in an array that matches a query. Here is my document structure:
doc: {
"userId":327238,
"assessmentId":115513,
"institutionId":1632,
"subjects":[
{"Id":238,"Included":false,"Rank":1},
{"Id":239,"Included":true,"Rank":4},
{"Id":240,"Included":false,"Rank":1},
{"Id":241,"Included":true,"Rank":10}
]
}
I would like to set 'Rank':0 only for array elements with 'Included':false. I have tried the below code but it sets 'Rank':0 for all the array elements.
query = {"assessmentId":115513, "institutionId":1632, "subjects":{"$elemMatch":{"Included":false}}}
update = {"$set":{"subjects.$[].Rank":0}}
db.test.update_many(query, update)
Any help would be appreciated. Thank you
You need to do with the positional operator + arrayFilters as follow:
mongo shell:
db.test.updateMany( {"doc.assessmentId":115513, "doc.institutionId":1632 } ,{"$set":{"doc.subjects.$[fs].Rank":0}},{arrayFilters:[{"fs.Included":false} ]} )
python:
query={"doc.assessmentId":115513, "doc.institutionId":1632 }
update={"$set":{"doc.subjects.$[fs].Rank":0}}
db.test.update_many( query ,update,array_filters=[{"fs.Included":False} ] )
explained: You define variable fs.Included:false in the arrayFilter that will be used to match the array objects in the update $set stage, and only the matched array objects will have the Rank set to 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.