2

I am new to mongodb and need some guidance with a query.

I have a collection named groups which looks like below.

{

    "_id" : ObjectId("jkhjkhkjhkj"),
    "name" : "some_name",
    "members" : [ 
        "product:naxi", 
        "product:tina", 
        "product:natalia"
    ]

},

{

    "_id" : ObjectId("jhkjhkjhkjhk"),
    "name" : "some_other_name",
    "members" : [ 
        "product:naxi", 
        "product:albert", 
        "product:natalia"
    ]

},

{

    "_id" : ObjectId("678687hjbnbmnm"),
    "name" : "some_new_name",
    "members" : [ 
        "product:peter, 
        "product:sonya", 
        "product:tom"
    ]

}

I want to delete product:naxi where ever it's present in any item's member array in group collection.

Below is how the end result should look like -

{

    "_id" : ObjectId("jkhjkhkjhkj"),
    "name" : "some_name",
    "members" : [ 
        "product:tina", 
        "product:natalia"
    ]

},

{

    "_id" : ObjectId("jhkjhkjhkjhk"),
    "name" : "some_other_name",
    "members" : [ 
        "product:albert", 
        "product:natalia"
    ]

},

{

    "_id" : ObjectId("678687hjbnbmnm"),
    "name" : "some_new_name",
    "members" : [ 
        "product:peter", 
        "product:sonya", 
        "product:tom"
    ]

}

How can this be done using pymongo.

Naxi
  • 1,504
  • 5
  • 33
  • 72
  • Does this answer your question? [How do I remove a string from an array in a mongodb document?](https://stackoverflow.com/questions/32002691/how-do-i-remove-a-string-from-an-array-in-a-mongodb-document) – turivishal Jun 20 '21 at 17:05

1 Answers1

4

$pull should do the trick:

db.groups.update(
    {},
    { $pull: { members: "product:naxi" } },
    { multi: true }
)
hisener
  • 1,431
  • 1
  • 17
  • 23