应对 mongodb修改多层数组对象时,一个$不够用。
栗子1:修改数组嵌套中的数据
一,原数据
{
"_id": ObjectId("5f7d88c342318e24c4003083"),
"id": "123456",
"arr": [
{
"name": "nickchen",
"condition": [
{
"type": "phone",
"contact": "159*******74"
},
{
"type": "email",
"contact": "159*******74@163.com"
}
]
},
{
"name": "hunter",
"condition": [
{
"type": "phone",
"contact": "159*******74"
},
{
"type": "email",
"contact": "159*******74@163.com"
}
]
}
]
}
二,SQL
//注意 $set条件与 arrayFilters条件 他们的数据层级关系。
db.lists.updateOne(
{id:"123456"},
{
$set:{
"arr.$[t].condition.$[val].contact":"123456789"
}
},
{
arrayFilters:[{
"t.name":"nickchen",
},{
"val.contact":"159*******74"
}],
multi:true
}
)
三,修改结果
{
"_id": ObjectId("5f7d88c342318e24c4003083"),
"id": "123456",
"arr": [
{
"name": "nickchen",
"condition": [
{
"type": "phone",
"contact": "123456789"
},
{
"type": "email",
"contact": "159*******74@163.com"
}
]
},
{
"name": "hunter",
"condition": [
{
"type": "phone",
"contact": "159*******74"
},
{
"type": "email",
"contact": "159*******74@163.com"
}
]
}
]
}
栗子二:删除数组中的元素
一,原数据
{
"_id": ObjectId("5f7d829842318e24c4003082"),
"id": "159789",
"arr": [
{
"name": "a1",
"ins": [
"10",
"11",
"12"
]
},
{
"name": "a2",
"ins": [
"13",
"14",
"15"
]
}
]
}
二,SQL
db.lists.updateOne(
{"id":"159789"},
{
$pull:{
"arr.$[t].ins":{$all:["10"]}
}
},
{
arrayFilters:[{
"t.name":"a1",
}],
multi:true
}
)
三,修改结构
{
"_id": ObjectId("5f7d829842318e24c4003082"),
"id": "159789",
"arr": [
{
"name": "a1",
"ins": [
"11",
"12"
]
},
{
"name": "a2",
"ins": [
"13",
"14",
"15"
]
}
]
}