MongoEngine:将字段添加到动态文档 [英] MongoEngine: Adding Fields to Dynamic Document
问题描述
我想将动态字段存储到文档中,但是每个文档可以具有不同的字段.
I would like to store dynamic fields to the document, but each document can have different fields.
例如:
Class SampleDoc(DynamicDocument):
xyz = StringField()
df = "field1"
a = SampleDoc()
a.df = "testing"
a.save()
如果运行上述程序,则mongodb文档如下所示.
If i run the above program, the mongodb document looks like the following.
{ "_id" : ObjectId("53905681e5ba5b3bfd1f5242"), "_cls" : "DataPoint", "df" : "testing" }
但是我想要的是字段名称应该是"field1"而不是"df".
but what i want is that the field name should be "field1" instead of "df" like this..
{ "_id" : ObjectId("53905681e5ba5b3bfd1f5242"), "_cls" : "DataPoint", "field1" : "testing" }
这只是示例代码,所以我知道df值是多少,但实际上我不知道df保持什么值.那么在存储时动态命名字段的方法是什么.
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.
还有一个类似的问题在Mongoengine中将密钥用作值,但是该解决方案建议使用DictField(),但我不想使用它.
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.
推荐答案
在源代码中查看BaseDocument.py之后,找到了解决方案.
Found the solution after looking at BaseDocument.py in the source code.
df = "field1"
a = SampleDoc()
a.__setattr__(df,"testing")
a.save()
这篇关于MongoEngine:将字段添加到动态文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!