MongoEngine:在DictField中存储EmbeddedDocument

rob*_*eer 12 python mongodb nosql mongoengine flask-mongoengine

我在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下?

rob*_*eer 19

我终于找到了问题的答案.实现这种模式的正确方法是使用a MapField.

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

class Inner(EmbeddedDocument):
  name = StringField()

class Outer(Document):
  outer_data = StringField()
  embed = MapField(EmbeddedDocumentField(Inner))
Run Code Online (Sandbox Code Playgroud)

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

  • 我尝试了这种方法,但保存它时,我发现"源SON对象需要类型为'dict'".你有一个解决方案,这将是非常有帮助的.谢谢 (3认同)