今天爱分享给大家带来pymongo与mongodb 如何更新数组中所有符合条件的元素【详细讲解】,希望能够帮助大家。
数据结构是多层嵌套数组:
{ "_id" : ObjectId("5de0c88a0f158bf0f60ff99a"), "province" : "陕西", "cityAndData" : [ {db.weather.update( {'province':'陕西','cityAndData.city':'西安','cityAndData.districtAndData.district':'长安'}, {$push: {"cityAndData.$.districtAndData.$[d].dateTimeAndData":'mydata'}}, {arrayFilters:[{'c.city':'西安'},{'d.district':'长安'}],upsert:false})"city" : "西安",
"districtAndData" : [
{
"district" : "长安",
"dateTimeAndData" : []
},
{
"district" : "临潼",
"dateTimeAndData" : []
}
]
},
{
"city" : "咸阳",
"districtAndData" : [
{
"district" : "咸阳",
"dateTimeAndData" : []
},
{
"district" : "三原",
"dateTimeAndData" : []
}
}
]
}需求:找出陕西省西安市长安区的dateTimeAndData属性中,插入一条数据 ‘mydata’
在mongodb shell中:
$[
]和arrayFilters配合起来使用,$是占位符,意思是在cityAndData数组的元素中,找到满足arrayFilters中对应过滤条件的元素,参考mongodb-identifier,注意要求mongodb版本号3.6及以上。如下,就能将’mydata’插入到dateTimeAndData中 db.weather.update( {'province':'陕西','cityAndData.city':'西安','cityAndData.districtAndData.district':'长安'}, {$push: {"cityAndData.$.districtAndData.$[d].dateTimeAndData":'mydata'}}, {arrayFilters:[{'c.city':'西安'},{'d.district':'长安'}],upsert:false})在pymongo中:
update方法已经逐渐废弃了。最好用update_one或者update_many,取决于你想更新一条还是多条符合条件的记录
self.mycol.update_one( dataUpdateQuery, {'$push'{'cityAndData.$.districtAndData.$[d].dateTimeAndData': dateTimeAndData}}, upsert=False, array_filters=[{'c.city':city},{'d.district':district}])为了看清楚分了几行写,注意upsert=False,不要用“:”代替“=”;array_filters也是作为参数出现的,不要加“”
其实看看官网的api就一目了然了(参考pymongo-update_one):