MongoEngine: Adding Fields to Dynamic Document

天大地大妈咪最大 提交于 2019-12-24 08:57:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!