小编rob*_*eer的帖子

MongoEngine:在DictField中存储EmbeddedDocument

我在MongoEngine中为一个Web项目建模一个MongoBD数据库.我想以稍微不寻常的方式存储数据,以便以后能够有效地查询它.

我们在MongoDB中的数据看起来像这样:

// "outer"
{  
  "outer_data": "directors",
  "embed": {
     "some_md5_key": { "name": "P.T. Anderson" },
     "another_md5_key": { "name": "T. Malick" },
     ...
   }
}
Run Code Online (Sandbox Code Playgroud)

我的第一直觉是在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
Run Code Online (Sandbox Code Playgroud)

换句话说,我基本上想要的是将ListDocument存储在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))
Run Code Online (Sandbox Code Playgroud)

我还希望在仍然使用DictField + EmbeddedDocument(作为dict"value")的同时为嵌套的"Inner"文档返回MongoEngine对象.我如何在MongoEngine中对此进行建模?它是否可能或者我是否必须天真地将所有数据置于通用DictField下?

python mongodb nosql mongoengine flask-mongoengine

12
推荐指数
1
解决办法
5320
查看次数

标签 统计

flask-mongoengine ×1

mongodb ×1

mongoengine ×1

nosql ×1

python ×1