Tanerax
Tanerax

Reputation: 5866

Using MongoDB, how do you remove embedded document from a list based on a match

I have a document and a embedded document using MongoEngine

class Sub(EmbeddedDocument):
    Id = StringField()
    User = StringField()
    Value = StringField()


class Main(Document):
    Value = StringField
    Values = ListField(EmbeddedDocumentField(Sub))

When I add new embedded documents into Main's 'Values' field, I generate a unique id to the list not to the collection, There can be multiple Sub in Main's 'values' each from different User's, I am trying to get MongoEngine to atomically remove a "Sub" value from the List, based on the ID and the User.

I have tried to run a select for the Main, then a update_one for the Sub itself

Main.objects(id=main_id).update_one(pull__values__id=sub_id) 

But all this seems to return is the index inside of the array. I know I could simply pull the Main, and go through the Values find the element and remove it, but I am trying to keep this atomic and with less chances of something being added to sub during the pull, iterate, update process.

Upvotes: 3

Views: 2669

Answers (1)

romanlv
romanlv

Reputation: 1458

Just use EmbeddedDocument class to pass sub_id

Main.objects(id=main_id).update_one(pull__values__id = Sub(Id=sub_id).Id )

Upvotes: 6

Related Questions