how to i push value in double nested array as shown in below code !!
{
"_id" : ObjectId("627ce38702f566ef8e89977a"),
"name" : "max",
"sub" : {
"type" : "maths",
"grades" : [
{
"semOne" : [
7,
8,
9
]
},
{
"semTwo" : [
9,
11,
12
]
}
]
}
}
let say i want to add 13 in semOne, how do i add ??
CodePudding user response:
You can use $push
in update with arrayFilters
.
db.collection.update({
"_id": ObjectId("627ce38702f566ef8e89977a")
},
{
$push: {
"sub.grades.$[g].semOne": 13
}
},
{
arrayFilters: [
{
"g.semOne": {
$exists: true
}
}
],
multi: true
})
Here is the Mongo playground for your reference.
CodePudding user response:
Probably like this:
const object = {
"_id" : ObjectId("627ce38702f566ef8e89977a"),
"name" : "max",
"sub" : {
"type" : "maths",
"grades" : [
{
"semOne" : [
7,
8,
9
]
},
{
"semTwo" : [
9,
11,
12
]
}
]
}
}
Try this:
object.sub.grades[0].semOne.push(13)
You might have facing error that .push is not a function, because "grades" is an array and here you have to define object position to push something.