Warix3
Warix3

Reputation: 101

MongoDB - Updating multiple subarrays in an array

Is it possible to remove elements from multiple subarrays inside of one big array? My structure looks something like this:

{
  "_id": {
    "$oid": ""
  },
  "users": [
    {
      "friends": [
        "751573404103999569"
      ]
    },
    {
      "friends": [
        "220799458408005633"
      ]
    }
  ]
}

I have a friend id and I need to remove it from all the "friends" arrays in the "users" array

Upvotes: 1

Views: 38

Answers (1)

R2D2
R2D2

Reputation: 10727

You can do with the positional operator $[] as follow:

db.no_more_friends.update({ "users.friends":"the_friend_id"  },{ $pull:{"users.$[].friends":"the_friend_id"}} ,{multi:true})

Just take in consideration that with {multi:true} it will perform the user id removal to all friends sub-arrays in all documents where "the_friend_id" is found

Upvotes: 1

Related Questions