考虑以下文档:
{
"countries" : [
{
"country" : "France",
"cities" : [
{
"city" : "Paris",
"population" : 100
}
]
},
{
"country" : "England",
"cities" : [
{
"city" : "London",
"population" : 100
},
{
"city" : "Liverpool",
"population" : 100
}
]
}
]
}
我想添加或更新城市(假设我们有方法upsert(country, city, population)
我们有3个案例:
- 国家和城市已经存在 - 这只是更新(替换城市对象)
- 国家存在但城市不存在 - 只需要
$push
大概
- 国家和城市不存在 - 需要准备和
$push
国家对象cities
大小数组1
其中包含新城市。
是否可以将所有这三个操作合并到一个查询中?
顺便一提,
我了解到$addToSet
但根据我的理解,它会比较所有对象的键,在我看来,它不会起作用,因为我也有cities
这是一个数组。
使用 ArrayFilters 进行更新相当简单:
q = {"_id":"1"}
update = {
"$set": {
"countries.$[i].cities.$[j].population": 200,
}
}
options = {
"arrayFilters": [
{
"i.country": "France"
},
{
"j.city": "Paris",
},
],
}
db.collection.updateOne(q, update, options)