我有这样的文件
{
"_id": {
"$oid": "5f33aca82b2fcf5324290ae1"
},
"active": true,
"addresses": [
{
"country": "IN",
"formatted": "xyz",
"locality": "San Francisco",
"postalCode": "7656",
"primary": true,
"region": "CA",
"streetAddress": "abc",
"type": "work"
},
{
"country": "US",
"formatted": "xyz",
"locality": "fdfdf",
"postalCode": "91608",
"primary": true,
"region": "CA",
"streetAddress": "def",
"type": "other"
}
]
}
address属性是多值的,我想在“ type” ==“ work”的情况下更新所有地址条目的“ streetAddress”。
但是当我在下面尝试此查询时,所有条目的“ streetAddress”都将得到更新。
mongo.db.test.update_one({'_id': ObjectId('5f33aca82b2fcf5324290ae1'), 'addresses.type':'work'}, {"$set":{'addresses.$[].streetAddress': "mno"}},upsert=True)
结果是
{
"_id": {
"$oid": "5f33aca82b2fcf5324290ae1"
},
"active": true,
"addresses": [
{
"country": "IN",
"formatted": "xyz",
"locality": "San Francisco",
"postalCode": "7656",
"primary": true,
"region": "CA",
"streetAddress": "mno",
"type": "work"
},
{
"country": "US",
"formatted": "xyz",
"locality": "fdfdf",
"postalCode": "91608",
"primary": true,
"region": "CA",
"streetAddress": "mno",
"type": "other"
}
]
}
您会看到两个条目都被修改了。
我正在使用flask-pymongo库。
答案 0 :(得分:1)
$[]
将更新数组的元素
但是$[<identifier>]
将仅更新与过滤器匹配的元素
您可以阅读更多here
我认为类似这样的方法应该起作用:
mongo.db.test.update_one({'_id': ObjectId('5f33aca82b2fcf5324290ae1')},
{"$set":{'addresses.$[addr].streetAddress': "mno"}},
{arrayFilters: [ { "elem.type": 'work' } ]},
upsert=True)
答案 1 :(得分:0)
Actual working code on widows 10 Mongo client
//data prep before:
db.test12.insert({
"active": true,
"addresses": [
{
"country": "IN",
"formatted": "xyz",
"locality": "San Francisco",
"postalCode": "7656",
"primary": true,
"region": "CA",
"streetAddress": "mno",
"type": "work"
},
{
"country": "US",
"formatted": "xyz",
"locality": "fdfdf",
"postalCode": "91608",
"primary": true,
"region": "CA",
"streetAddress": "mno",
"type": "other"
}
]
});
--
//data changes post update, you need to use $ to access array elements in the address array
> db.test12.updateOne({"addresses.type":"work"},{$set:{"addresses.$.streetAddress":"St Johns road"}});
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.test12.find().pretty();
{
"_id" : ObjectId("5f492467e551d4c998f3c9ca"),
"active" : true,
"addresses" : [
{
"country" : "IN",
"formatted" : "xyz",
"locality" : "San Francisco",
"postalCode" : "7656",
"primary" : true,
"region" : "CA",
"streetAddress" : "St Johns road",
"type" : "work"
},
{
"country" : "US",
"formatted" : "xyz",
"locality" : "fdfdf",
"postalCode" : "91608",
"primary" : true,
"region" : "CA",
"streetAddress" : "mno",
"type" : "other"
}
]
}
>