我正在 MongoEngine 中为一个 Web 项目建模 MongoDB 数据库。我想以一种稍微不寻常的方式存储数据,以便以后能够有效地查询它。
我们在 MongoDB 中的数据看起来像这样:
// "outer"
{
"outer_data": "directors",
"embed": {
"some_md5_key": { "name": "P.T. Anderson" },
"another_md5_key": { "name": "T. Malick" },
...
}
}
我的第一直觉是在 MongoEngine 中像这样建模:
class Inner(EmbeddedDocument):
name = StringField()
class Outer(Document):
outer_data = StringField()
embed = DictField(EmbeddedDocument(Inner)) # this isn't allowed but you get the point
换句话说,我本质上想要的是将EmbeddedDocument存储在ListField中,而是存储在DictField中,每个EmbeddedDocument都有动态键。
允许使用ListField的示例供参考:
class Inner(EmbeddedDocument):
inner_id = StringField(unique=True) # this replaces the dict keys
name = StringField()
class Outer(Document):
outer_data = StringField()
embed = ListField(EmbeddedDocument(Inner))
我更希望为嵌套的“内部”文档返回 MongoEngine 对象,同时仍然使用 DictField + EmbeddedDocument (作为字典“值”)。我如何在 MongoEngine 中对此进行建模?是否有可能,或者我是否必须天真地将所有数据放在通用 DictField 下?
class Inner(EmbeddedDocument):
name = StringField()
class Outer(Document):
outer_data = StringField()
embed = EmbeddedDocumentField(Inner)