Search code examples
pythonmongodbmongoengineembedded-documents

Mongoengine: dynamic Fields with EmbededDocuments as values


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?


Solution

  • 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()