MongoEngine:在DictField中存储EmbeddedDocument

时间:2014-11-18 10:21:27

标签: python mongodb mongoengine flask-mongoengine nosql

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

我们在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

换句话说,我基本上想要的是将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))

我更愿意为嵌套的"内部"返回MongoEngine对象。仍在使用DictField + EmbeddedDocument的文档(作为dict" value")。我如何在MongoEngine中对此进行建模?它是否可能或者我是否必须天真地将所有数据放在通用的DictField下?

1 个答案:

答案 0 :(得分:17)

我终于找到了问题的答案。实现此模式的正确方法是使用MapField

MongoEngine中的相应模型如下所示:

class Inner(EmbeddedDocument):
  name = StringField()

class Outer(Document):
  outer_data = StringField()
  embed = MapField(EmbeddedDocumentField(Inner))

在MongoDB中,所有键都需要是字符串,因此不需要指定"字段类型"对于MapField中的键。

相关问题