skip to Main Content

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


  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.

    Login or Signup to reply.
  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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search