How to remove an element from an array property in mongo collection

Viewed 929

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.

1 Answers

$pull should do the trick:

db.groups.update(
    {},
    { $pull: { members: "product:naxi" } },
    { multi: true }
)
Related