0

I'm trying to update a deeply nested subdocument in mongo but to no success.

I want to update the advisors field in the subGroups array. Based on the conditions.

e.g If groupName: 'others' and subGroupName: 'a' I would like to push to advisors array.

I have tried all possible solutions i could find on StackOverflow, but none worked. That's why I'm posting a new question.

{
"_id" : ObjectId("5adf46105129180001c41bae"),
"groups" : [ 
    {
        "groupName" : "others",
        "subGroups" : [ 
            {
                "subGroupName" : "a",
                "students" : [],
                "advisors" : [ 
                    "lonard",
                ]
            }, 
            {
                "subGroupName" : "bots",
                "students" : [],
                "advisors" : [ 
                    "test"
                ]
            },
        ]
    }, 
    {
        "groupName" : "masters",
        "subGroups" : [ 
            {
                "subGroupName" : "a",
                "students" : [],
                "advisors" : []
            }, 
            {
                "subGroupName" : "slots",
                "students" : [],
                "advisors" : []
            }
        ]
    }
],
"__v" : 0

}

Here's what i've tried.

ClassGroup.update(
  {
    university,
    groups: {
      $elemMatch: {
        groupName: 'others',
        "subGroups.subGroupName": 'bots'
      }
    }
  },
  {
    $push: { "groups.$[outer].subGroups.$[inner].advisors": advisors }
  },
  {
    arrayFilters: [
      { "outer.groupName": 'others' },
      { "inner.subGroupName": 'bots' }
    ]
  }
)

Along with a number of other workarounds, But it doesn't work. I'm not sure what I'm missing.

N.B this post was marked as duplicate, but on trying to link to the duplicate I'm getting an error.

MongoError: cannot use the part (groups of groups.$[outer].subGroups.$[inner].advisors) to traverse the element ({groups: [ { groupName: \"others\", ... Thanks.

  • Hi @Neil Lunn, I'm updated my solution to the link you provided but now i'm getting an error – Fowotade Babajide May 02 '18 at 22:59
  • That's because the MongoDB version you are using does not support `arrayFilters` and named positional updates. That's not the **only** solution in the answer, as it does explain ( and originally ) that nested arrays like this are not supported in earlier MongoDB versions. Either update MongoDB, or flatten your array structure as the answer actually explains. – Neil Lunn May 02 '18 at 23:50

0 Answers0