1

My mongodb document(table) 'Org_unit' looks like this:

{
    "_id": ObjectId("0894f016e6e2e073c19e051")
    "allowedusers": [
        "admin",
        "Fred",
        "Bob",
        "Layneh"
    ],
    "name": "News management",
    "divisions": [
        {
            "allowedusers": [
                "admin",
                "Larry",
                "Bob",
                "Harry",
                "Fred"
            ],
            "_id": ObjectId("60894f016e6e2e073c19e052"),
            "name": "Finances",
            "credentials": [
                {
                    "_id": ObjectId("94f0944f016e6e2e2342cc"),
                    "name": "FNB - FA",
                    "userName": "[email protected]",
                    "password": "examplePassword!@#"
                }
            ]
        },
        {
            "allowedusers": [
                "admin",
                "Larry",
                "Bob",
                "Harry",
                "Fred"
            ],
            "_id": ObjectId("60894f016e6e2e073c19e052"),
            "name": "Development",
            "credentials": [
                {
                    "_id": ObjectId("94f0944f016e6e2e2342cc"),
                    "name": "FNB - DEV",
                    "userName": "[email protected]",
                    "password": "examplePassword!@#"
                }
            ]
        }
    ],
    "__v": 11
}

This is my fist post here, hello! Ok so I have been at this for a few days now and I just cant get this right.

What I am trying to do:

Within the "divisions" array, I want to remove "Fred" from the "allowedusers" array in each object "division" that he appears in.

What I have tried

I am still very new, about a week in. I have tried many times, but the closest I have gotten was this:

Org_unit.updateMany({name: "News management"}, { $pull: {'divisions': {'allowedusers': "Fred"}}},{ multi: true })

^^ This deleted the entire division if he appeared in its "allowedusers" array

Any guidance with this is massively appreciated Thank you in advance.

PS: (Since this is my first question posted, please let me know how I can improve my questions in the future!)

1 Answer 1

1

Demo - https://mongoplayground.net/p/kR_NmQNO52y

Use $[]

The all positional operator $[] indicates that the update operator should modify all elements in the specified array field.

db.collection.update({
  name: "News management"
},
{
  $pull: {
    "divisions.$[].allowedusers": "Fred"
  }
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Seems I need to do more document digging on $.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.