0

I have been searching all day to figure out how to do a simple delete for one element inside a document that is inside a collection. I am fairly new to mongo scripts so bear with me.

I am currently using this script to see a certain document:

 db.getCollection('roles').deleteOne({"_id": "e9b4afad-cb5c-4588-9560-161867faa5b7"})

This is what the document shows in Robo3T after the it is executed:

{
    "_id" : "e9b4afad-cb5c-4588-9560-161867faa5b7",
    "appIds" : [ 
        "rpt", 
        "wc", 
        "bw"
    ],
}

I am simply wanting to remove "rpt" from appIds. I have tried this so far and it doesn't work:

db.getCollection('roles').find({"_id": "e9b4afad-cb5c-4588-9560-161867faa5b7"}).remove({"appIds": "rpt"})

Any documentation that'll point me in the right direction?

Thanks!

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
BluePilot
  • 373
  • 3
  • 15

1 Answers1

1

It is not an easy task but I believe $pull will do the work.

The $pull operator removes from an existing array (in a doc) all instances of a value or values that match a specified condition.

I would try,

db.roles.update(
  { },
  { $pull: { appIds: "rpt"}},
  { multi: true }
)

Let me know if it works...

If you want to update a specific id just add it in the first part {}, -> {_id: *****},

See the great documentation of MongoDB at https://docs.mongodb.com/manual/reference/operator/update/pull/

Elad Rubi
  • 593
  • 4
  • 7