Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a MongoEngine document using a python dict?

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"
        }
    ]
})
like image 588
gitaarik Avatar asked Sep 25 '13 10:09

gitaarik


People also ask

How do you update a record in MongoDB Python?

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.

How do I Upsert MongoDB in Python?

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.


1 Answers

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.

like image 191
Fydo Avatar answered Sep 28 '22 03:09

Fydo