Search code examples
arraysmongodbpull

How to delete the element from document in Mongodb?


I have this collection in MongoDB and I want to delete "Bangalore" as shown below.

{
    "_id": "1",
    "UserName": "Mike",
    "UserDetails": [{
        "UserCountryName": "India",
        "UserLocation": [
            "Bangalore",
            "Chennai",
            "Delhi",
            "Mumbai"
        ]
    }]
}

I tried the below query but it didn't work. The whole UserDetails array is getting deleted. I want only "Banglore" to be deleted. Please help.

db.user.update( 
  { }, 
  { $pull: { "UserDetails": {"UserLocation":"Bangalore"} } } 
)

Solution

  • Here is the correct option:

     db.user.update({},
    {
     $pull: {
     "UserDetails.$[].UserLocation": "Bangalore"
     }
    },
    {
      multi: true
    })
    

    Explained: This is removing the value from all UserDetails.$[].UserLocation array elements in all documents in the user collection.

    playground

    playground(in option when more then one values need to be removed)