3
votes

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.

2

2 Answers

4
votes

Found the solution after looking at BaseDocument.py in the source code.

df = "field1"
a = SampleDoc()
a.__setattr__(df,"testing")
a.save()
1
votes

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" }