Update a MongoEngine document using a python dict?

gitaarik picture gitaarik · Sep 25, 2013 · Viewed 11.3k times · Source

Is it possible to update a MongoEngine document using a python dict?

For example:

class Pets(EmbeddedDocument):
    name = StringField()

class Person(Document):
    name = StringField()
    address = StringField()
    pets = ListField(EmbeddedDocumentField(Pets))

p = Person()
p.update_with_dict({
    "name": "Hank",
    "address": "Far away",
    "pets": [
        {
            "name": "Scooter"
        }
    ]
})

Answer

Fydo picture Fydo · Oct 25, 2018

Pretty late to the game here, but FWIW, MongoEngine has a build in solution for this.

Regardless if you want to create or update you can do the following:

class Pets(EmbeddedDocument):
    name = StringField()

class Person(Document):
    name = StringField()
    address = StringField()
    pets = ListField(EmbeddedDocumentField(Pets))

p = Person(**{
    "name": "Hank",
    "address": "Far away",
    "pets": [{"name": "Scooter"}]
})
p.save()

Only difference for update is you need to stick in an id. That way mongoengine won't duplicate a doc with an existing id and update it instead.