简体   繁体   中英

Remove objects within array in MongoDB

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" : "david@gmail.com"
        }, 
        {
            "name" : "Pablo",
            "last_name" : "Claros",
            "telephone" : "628721784",
            "email" : "pablo@gmail.com"
        }
    ]
}

// 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" : "dasd@gmail.com"
        }, 
        {
            "name" : "Pablo",
            "last_name" : "Claros",
            "telephone" : "628721784",
            "email" : "pablo@gmail.com"
        }
    ]
}

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 
                      }
                     )

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 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM