简体   繁体   English

更新与 mongodb 中的查询匹配的多个数组元素

[英]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.我正在使用 python 代码更新与查询匹配的数组中的多个元素。 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.我想仅为具有“包含”的数组元素设置“排名”:0:假。 I have tried the below code but it sets 'Rank':0 for all the array elements.我已经尝试了下面的代码,但它为所有数组元素设置了 'Rank':0 。

 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:您需要使用位置运算符 + arrayFilters 如下:

mongo shell:蒙戈 shell:

db.test.updateMany( {"doc.assessmentId":115513, "doc.institutionId":1632 } ,{"$set":{"doc.subjects.$[fs].Rank":0}},{arrayFilters:[{"fs.Included":false} ]}  )

python: 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解释:您在 arrayFilter 中定义变量 fs.Included:false 将用于匹配更新 $set 阶段中的数组对象,并且只有匹配的数组对象的 Rank 设置为 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM