我想更新所有与某个字段匹配的文档并移动此元素(并且我想保留此元素的所有属性)。
数据集:
[{
"name": "Guillaume",
"childrens": [{
"name": "Robert",
"degree": "License"
}
],
"students": [
{
"name": "Hélène",
"degree": "License"
}]
},
{
"name": "Mathilde",
"childrens": [ {
"name": "Lucie",
"degree": "License"
}],
"students": [
{
"name": "Michel",
"degree": "License"
}]
}]
For example, I would like to update "childrens.degree" = Master to all childrens that match name "Robert" and move this child to "students". Expected result :
[{
"name": "Guillaume",
"childrens": [],
"students": [
{
"name": "Hélène",
"degree": "License"
},
{
"name": "Robert",
"degree": "Master"
}]
},
{
"name": "Mathilde",
"childrens": [
{
"name": "Lucie",
"degree": "License"
}],
"students": [
{
"name": "Michel",
"degree": "License"
}]
}]
我更新了与Robert匹配的所有文档,但未能将子Robert移入学生
db.person.updateMany(
{"childrens.name": "Robert" },
{
$set: {
"childrens.$[child].degree": "Master"
}
},
{ arrayFilters: [ {"child.name": "Robert"} ] }
)
我尝试了:
db.person.updateMany(
{"childrens.name": "Robert" },
{
$set: {
"childrens.$[child].degree": "Master",
$push: {
"students": "childrens.$[child]"
}
}
},
{ arrayFilters: [ {"child.name": "Robert"} ] }
)
2条答案
按热度按时间zkure5ic1#
你想使用pipelined updates来完成这个任务,现在我们可以从所有的“roberts”中过滤出children数组,同时使用
concatArrays
将它们添加到students数组(同时也改变它们的学位),如下所示:Mongo Playground
vhmi4jdf2#
Playground