How to upgrade with json Mongoengine DynamicDocument

I am trying to find an elegant way to update an existing MongoDB document with data retrieved from a web page as json. The problem is that I do not know in advance which fields will be updated, so I can not use set__field , I only have a json representation of the fields that will be updated in my MongoDB document. In addition, I use DynamicDocuments, so new fields can be set in the document. eg:.

class Study(DynamicDocument): study_accession_nr = StringField() study_name = StringField() study_type = StringField() 

and json might look like:

 {"_id" : "123", "study_name" : "Statistics"} 

or

 {"_id" : "123", "study_type" : "research", "study_name" : "Statistical analysis"} 

I can do this easily from the console or using pymongo, but I don’t know how to do it using Mongoengine, unless I manually setattr (myDocInstance, nameOfField, val), which does not look so elegant for me. Thanks!

+6
source share
2 answers

You can simply pass data when the class starts:

 data = {"_id" : "123", "study_type" : "research", "study_name" : "Statistical analysis"} doc = Study(**data) 

To update existing models, you can either call the 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() 
+5
source

Normal MongoEngine. In my case, I get a form from x-editable that has fields with the same name as my schema, so I can go directly to the database with that.

 ActivityType.objects.filter(id=request.form['pk']).update(**{'set__'+request.form['name']: request.form['value']}) 
0
source

All Articles