mongodbmongodb-querymongodb-update

MongoDB - Remove object element in array inside another object


Keep it short. I have:

{
  _id: "694201337",             //_id => user id
  skills: [
    {
      sId: "420",       //sId => Skill id
      title: "Coding",
      level: 69,
      goals: [
        {
          gId: "1337",   //gId => Goal id
          title: "3hr/week",
          text: "Code atleast 3 hours every week"
        },
        {
          gId: "12345",   //gId => Goal id
          title: "Simulation",
          text: "Create a python simulation game"
        } 
      ]
    }
  ]
}
        

I want to remove a goal object from the goals array, from a specific skill object from the skills array, from the user.

So if I want to remove the goal with the id (gId) of "1337", it should look like this after:

{
  _id: "694201337",             //_id => user id
  skills: [
    {
      sId: "420",       //sId => Skill id
      title: "Coding",
      level: "69",
      goals: [
        {
          gId: "12345",   //gId => Goal id
          title: "Simulation",
          text: "Create a python simulation game"
        } 
      ]
    }
  ]
}

I have my collection as:

const Collection

What is the correct command to get the result I want? I should point out that all IDs are known.

Something like:

Collection.update({_id: "694201337"}, {$pull: { skills : {skill : {goal.gId: "1337"}}}

Solution

  • You can work with dot notation and all positional operator ($[]) to remove all the "goal" elements with gId: "1337.

    db.collection.update({
      _id: "694201337",
      "skills.goals.gId": "1337"
    },
    {
      $pull: {
        "skills.$[].goals": {
          gId: "1337"
        }
      }
    })
    

    Demo @ Mongo Playground