Clara
Clara

Reputation: 3035

How to update from json a Mongoengine DynamicDocument

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!

Upvotes: 8

Views: 4437

Answers (2)

mianos
mianos

Reputation: 962

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

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

Upvotes: 1

Ross
Ross

Reputation: 18111

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()

Upvotes: 8

Related Questions