Reputation: 1299
I have been using MapField till now as:
class Game(EmbeddedDocument):
iscomplete = BooleanField()
score = IntField()
#other not dynamic fields
class Progress(Document):
user = ReferenceField(User, dbref=True)
games = MapField(EmbeddedDocumentField(Game))
created_at = DateTimeField()
updated_on = DateTimeField()
I need to convert games to a ReferenceField.
I want to create Document with dynamic fields/keys but embeddedDocument as the values, so that I can have a document like:
{
"game1": {
"iscomplete": true,
"score": 23,
},
"game2": {
"iscomplete": false,
"score": 10,
}
}
Is t here anyway I can achieve it?
Upvotes: 3
Views: 6633
Reputation: 203
[Note - use mongoengine and pandas for below code]
Below code is for read csv file and insert in mongod dynamic collection.
Example -: to save csv data in mongod collection dynamically.
import mongoengine as me
class DynamicDoc(me.DynamicDocument):
any_field = me.StringField()
import pandas as pd
all_csv_records = data_frame.to_dict('records')
data_frame = pd.read_csv(file_path)
for data in all_csv_records:
report_data = DynamicDoc()
DynamicDoc.any_field = str('temp_data')
for col, row in data.iteritems():
report_data[col] = row
report_data.save()
Upvotes: 0
Reputation: 5529
You can achive that using dynamic document in mongengine:
DynamicDocument documents work in the same way as Document but any data / attributes set to them will also be saved
So, you remove the games field, and add later your dynamic field games as, game1, game2, etc fields, they will be saved.
class Game(EmbeddedDocument):
iscomplete = fields.BooleanField()
score = fields.IntField()
class Progress(DynamicDocument):
user = ReferenceField(User, dbref=True)
created_at = DateTimeField()
updated_on = DateTimeField()
p = Progress()
p.game1 = Game(iscomplete=True, score=10)
p.game2 = Game(iscomplete=False, score=5)
p.save()
Upvotes: 4