更新双嵌套数组脚本
Update double nested array script
我正在尝试编写脚本以在不删除整个数组的情况下在双嵌套数组中添加新字段。
我正在尝试向 School.teacher.class
、
添加新字段 totalStudents
这是结构:
Work: [...],
School: [{
name: {type: String, default: ''},
teacher:
[{
class: {
enabled: {type: Boolean, default: true},
grade: [{type: String, default: ''}],
},
test: {
enabled: {type: Boolean, default: false},
duration: {type: Number, default: 5},
},
score: {type: Number, default: 0},
}]
curve:
[{
lower: {type: Number, default: 0},
upper: {type: Number, default: 0},
withinBoundary: {type: Boolean, default: false},
outsideBoundary: {type: Boolean, default: false},
enabled: {type: Boolean, default: true}
}]
}],
我写的代码:
db.colllection.updateMany({}, {$set: {School: [{teacher:[{class:{totalStudents: null}}]}]}})
首先,您必须在 class
对象的架构中添加该字段,
class: {
enabled: {type: Boolean, default: true},
grade: [{type: String, default: ''}],
totalStudents: { type: Number }
},
如果您尝试插入所有数组元素,那么您可以尝试使用位置数组运算符在所有元素中设置字段,
db.collection.updateMany({},
{
$set: {
"School.$[].teacher.$[].class.totalStudents": null
}
})
我正在尝试编写脚本以在不删除整个数组的情况下在双嵌套数组中添加新字段。
我正在尝试向 School.teacher.class
、
totalStudents
这是结构:
Work: [...],
School: [{
name: {type: String, default: ''},
teacher:
[{
class: {
enabled: {type: Boolean, default: true},
grade: [{type: String, default: ''}],
},
test: {
enabled: {type: Boolean, default: false},
duration: {type: Number, default: 5},
},
score: {type: Number, default: 0},
}]
curve:
[{
lower: {type: Number, default: 0},
upper: {type: Number, default: 0},
withinBoundary: {type: Boolean, default: false},
outsideBoundary: {type: Boolean, default: false},
enabled: {type: Boolean, default: true}
}]
}],
我写的代码:
db.colllection.updateMany({}, {$set: {School: [{teacher:[{class:{totalStudents: null}}]}]}})
首先,您必须在 class
对象的架构中添加该字段,
class: {
enabled: {type: Boolean, default: true},
grade: [{type: String, default: ''}],
totalStudents: { type: Number }
},
如果您尝试插入所有数组元素,那么您可以尝试使用位置数组运算符在所有元素中设置字段,
db.collection.updateMany({},
{
$set: {
"School.$[].teacher.$[].class.totalStudents": null
}
})