问题
I would like to store dynamic fields to the document, but each document can have different fields.
for eg:
Class SampleDoc(DynamicDocument):
xyz = StringField()
df = "field1"
a = SampleDoc()
a.df = "testing"
a.save()
If i run the above program, the mongodb document looks like the following.
{ "_id" : ObjectId("53905681e5ba5b3bfd1f5242"), "_cls" : "DataPoint", "df" : "testing" }
but what i want is that the field name should be "field1" instead of "df" like this..
{ "_id" : ObjectId("53905681e5ba5b3bfd1f5242"), "_cls" : "DataPoint", "field1" : "testing" }
This is just a sample code so i know what df value is, but in real i don't know what value df holds. So what is the way to name a field dynamically while storing.
There is a similar question using key as value in Mongoengine, but the solution suggests to use DictField(), but i don't want to use it.
回答1:
Found the solution after looking at BaseDocument.py in the source code.
df = "field1"
a = SampleDoc()
a.__setattr__(df,"testing")
a.save()
回答2:
In the mongoDB shell this worked for me:
df = "field1"
a = {}
a[df.toString()] = "testing" //use [] and toString here
db.test.save(a)
db.test.find(a)
{ "_id" : ObjectId("539062f5944a6efde79f7c1d"), "field1" : "testing" }
来源:https://stackoverflow.com/questions/24059560/mongoengine-adding-fields-to-dynamic-document