MongoEngine:将EmbeddedDocument存储在DictField中

问题描述 投票:0回答:2

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

python mongodb mongoengine flask-mongoengine nosql
2个回答
25
投票
我终于找到了问题的答案。实现此模式的正确方法是使用

MapField



MongoEngine 中对应的模型如下:

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

在 MongoDB 中,所有键都需要是字符串,因此无需为

MapField

 中的键指定“字段类型”。


0
投票
在我的例子中,它可以在没有 MapField 的情况下工作

class Inner(EmbeddedDocument): name = StringField() class Outer(Document): outer_data = StringField() embed = EmbeddedDocumentField(Inner)
    
© www.soinside.com 2019 - 2024. All rights reserved.