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"
        }
    ]
})
                You can update a record, or document as it is called in MongoDB, by using the update_one() method. The first parameter of the update_one() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated.
Updating a document is a common task when you're using MongoDB to store your data, and it's easy to get this job done with a simple Python script. With the help of the PyMongo library, you can use the update_one() and find_one_and_update() methods to easily update MongoDB documents in Python.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With