How to update the nested array object field and push an array with an object if array doesn't exist

I have a collection course assignment as shown below:

[
  {
    "_id": ObjectId("64bfd2552c1771905ea095a8"),
    "status": "In Progress",
    "sectionDetails": [
      {
        sectionId: ObjectId("64bfcf3164df731eb1e40e87"),
        status: "In Progress",
        slideQuestionAnswer: [
          {
            "slideId": ObjectId("64bfe10564c2850b70b613d2"),
            "answers": [
              ObjectId("64c00ff20f4d05a55793759f"),
              ObjectId("64c01003a55c370435f7a6d8"),
              ObjectId("64c0100cf3267c399667d1b3"),
            ]
          }
        ]
      }
    ]
  }
]

I am able to do a query to update the answers of slideQuestionAnswer by matching the slideId with the below query

db.collection.update({
  "_id": ObjectId("64bfd2552c1771905ea095a8")
},
{
  $set: {
    "sectionDetails.$[sd].slideQuestionAnswer.$[sqa].answers": [
      ObjectId("64c00ff20f4d05a55793759f")
    ]
  }
},
{
  "arrayFilters": [
    {
      "sd.sectionId": ObjectId("64bfcf3164df731eb1e40e87")
    },
    {
      "sqa.slideId": ObjectId("64bfe10564c2850b70b613d2")
    }
  ]
})

But I want to push newer objects to slideQuestionAnswer if it is blank along with the above query. How can I do it?

Check the answer provided in the following as it seems more or less the same issue.

2 Likes

Thanks for sharing the link. Really appreciated.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.