How to update from json a Mongoengine DynamicDocument
mongoengine, python
Solution
You can just pass the data when you initiate the class:
data = {"_id" : "123", "study_type" : "research", "study_name" : "Statistical analysis"}
doc = Study(**data)
To update existing models you can either call update (preferred) or change the model and call save.
eg:
Doc.update(set__VAR=Val, set__VAR2=Val2)
Or
setattr(Doc, 'VAR', val)
setattr(Doc, 'VAR2', val2)
Doc.save()
or
Doc.VAR = val
Doc.VAR2 = val2
Doc.save()
Problem
I am trying to find an elegant way of updating an existing MongoDB document with the data received from a web page as json. The problem is that I do not know in advance which fields are going to be updated - so I can't use set__field, I only have a json representation of the fields to be updated in my MongoDB document. Plus I am using DynamicDocuments, so there might be new fields to be set on the document. e.g.: ``` class Study(DynamicDocument): study_accession_nr = StringField() study_name = StringField() study_type = StringField() ``` and the json may look like - for example: ``` {"_id" : "123", "study_name" : "Statistics"} ``` or ``` {"_id" : "123", "study_type" : "research", "study_name" : "Statistical analysis"} ``` I can do it easily from the console, or using pymongo, but I don't know how to do this using Mongoengine, unless I manually setattr(myDocInstance, nameOfField, val), which does not look so elegant to me. Thanks!