0

I need to remove all the objects within array who meet the conditions i will show down below. I'll let here the documents and an example of what i've done.

//document 1
{
    "_id" : ObjectId("5ec73abebd7e4d618a057350"),
    "code" : "X20",
    "title" : "Full stack developer",
    "location" : "Paris",
    "date" : ISODate("2020-05-22T02:36:46.272Z"),
    "candidates" : [ 
        {
            "name" : "David",
            "last_name" : "Broncano",
            "telephone" : "642025552",
            "email" : "[email protected]"
        }, 
        {
            "name" : "Pablo",
            "last_name" : "Claros",
            "telephone" : "628721784",
            "email" : "[email protected]"
        }
    ]
}

// document 2
{
    "_id" : ObjectId("4ec73abebd7e4d618a057350"),
    "code" : "X50",
    "title" : "Full stack developer",
    "location" : "Madrid",
    "date" : ISODate("2020-05-22T02:36:46.272Z"),
    "candidates" : [ 
        {
            "name" : "Maria",
            "last_name" : "Mars",
            "telephone" : "642024582",
            "email" : "[email protected]"
        }, 
        {
            "name" : "Pablo",
            "last_name" : "Claros",
            "telephone" : "628721784",
            "email" : "[email protected]"
        }
    ]
}

So i need to remove all the candidates where location is Madrid.I have done this but it removes the field. Is it possible to just remove the content of it using $pull or something?

db.offers.update(
                      { location : "Madrid"},
                      { 
   $unset:{
      "candidates":""
   }   } , 
                      { 
                          multi : true 
                      }
                     )
2
  • You can to use the $pull update operator to remove specific nested documents based on a condition. Commented Jun 5, 2020 at 8:29
  • Yes but i don't know how to put it here because the condition is not inside the array as u can see. I can not put $pull: candidates : name :"x" or anything similar because it wouldn't do what i need. Commented Jun 5, 2020 at 8:34

1 Answer 1

1

According to my understanding, you need to just clear the candidates array and maintain that as candidates: []. For this, you can use use $set operator to set candidates to [] based on your condition

db.offers.update({ location : "Madrid"}, { $set:{ "candidates": [] } } , { multi : true })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.