3

Here is dummy JSON:

{
    "_ID": ObjectId('xdfdsf'),
        "array": [
            {
                "name": "Jon",
                "permissions": [
                    "update",
                    "delete",
                    "create"
                ]
            },
            {
                "name": "Ben",
                "permissions":[
                    "update"
                ]
            }
        ]
}

And so on. I want to create a query that will search the array, find element in array which has name "Ben" and pushes new permission into the array.

It's probably relatively simple to do but I got completely lost.

MazMat
  • 1,904
  • 3
  • 12
  • 24

2 Answers2

2

You can use $ positional operators to do such updates.

Try this :

db.collection_name.update({
    "array.name" : "Ben"
},{
    $push : {
        "array.$.permissions" : "new_permission"
    }
}

Read more about $(update) positional operator in official MongoDb docs for detailed information.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52
  • 1
    Haha, yes, I just posted my own answer, I was missing the "$", I guess it's monday for you, thanks! – MazMat Jul 08 '19 at 09:06
2

Sadly, Zoti's answer was incorrect, but I finally got it working:

db.myCollection.update( { "array.name": "Ben"}, {$push: {"array.$.permissions": "read"}})
MazMat
  • 1,904
  • 3
  • 12
  • 24