I'm trying to write a script to add a new field in a double nested array without deleting the entire array.
I'm trying to add a new field totalStudents
to School.teacher.class
,
This is the structure:
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}
}]
}],
The code that I wrote:
db.colllection.updateMany({}, {$set: {School: [{teacher:[{class:{totalStudents: null}}]}]}})
CodePudding user response:
First of all, you have to add that field in your schema in class
object,
class: {
enabled: {type: Boolean, default: true},
grade: [{type: String, default: ''}],
totalStudents: { type: Number }
},
If you are trying to insert in all array elements then you can try positional array operator to set field in all the elements,
db.collection.updateMany({},
{
$set: {
"School.$[].teacher.$[].class.totalStudents": null
}
})