Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

python - update multiple array elements matching a query in mongodb

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...