1

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 ??

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

hi atul, is ther any other way using $push , asking out of curiosity !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.