Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 963
Shipra Avatar asked Apr 05 '26 22:04

Shipra


1 Answers

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()
like image 164
sergiuz Avatar answered Apr 08 '26 13:04

sergiuz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!