【问题标题】:MongoEngine: storing EmbeddedDocument in DictFieldMongoEngine:将 EmbeddedDocument 存储在 DictField 中
【发布时间】:2014-11-18 10:21:27
【问题描述】:

我正在为一个 Web 项目在 MongoEngine 中为 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 中,而不是存储在每个 EmbeddedDocument 具有动态键的 DictField 中。

被允许的示例与 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))

我更希望在仍然使用 DictField + EmbeddedDocument(作为 dict“值”)的同时为嵌套的“内部”文档返回 MongoEngine 对象。如何在 MongoEngine 中建模?甚至有可能还是我必须天真地将所有数据放在通用 DictField 下?

【问题讨论】:

    标签: python mongodb mongoengine flask-mongoengine nosql


    【解决方案1】:

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

    MongoEngine中对应的模型如下:

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

    在 MongoDB 中,所有键都需要是字符串,因此无需为 MapField 中的键指定“字段类型”。

    【讨论】:

    • 我尝试了这种方法,但在保存时它给了我“源 SON 对象需要是 'dict' 类型”。您对此有解决方案将非常有帮助。谢谢
    • 对我来说,embed 是一个字典列表。所以,embed = ListField(EmbeddedDocumentField(Inner)) 为我工作
    猜你喜欢
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    相关资源
    最近更新 更多