Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove object element in array inside another object in mongoDB

Keeping 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 goals array, from a specific skill object from skills array, from user.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
 _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 id’s 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading