【问题标题】:Using nested/embedded documents in Mongoengine with Python在 Python 中使用 Mongoengine 中的嵌套/嵌入文档
【发布时间】:2021-07-26 14:50:05
【问题描述】:

我想在 Mongodb 中使用嵌套值,从文档中我了解到这是通过嵌入式文档完成的。如果有其他方法请告诉我。

我有当前代码:

class compute_instances_subtype(EmbeddedDocument):
    label_name = StringField()

class Post(Document):
    title = StringField(max_length=120, required=True)
    author = StringField(required=True)
    tags = ListField(StringField(max_length=30))
    compute_instances = ListField(EmbeddedDocumentField(compute_instances_subtype))

post = Post(title="Quora rocks", author="Ross", tags=['tutorial', 'how-to'])

add_test0_label = compute_instances_subtype()
add_test0_label.title = "test0"
add_test0_label.label_name= "value"

add_test1_label= compute_instances_subtype()
add_test1_label.title = "test1"
add_test1_label.label_name= "value"

post.compute_instances.append(add_test0_label)
post.compute_instances.append(add_test1_label)
post.save()

但我的问题是该文档没有 compute_instances 字段的对象的名称,它只是说 0 和 1:

id : 60fec94dbb81d98abb557523
title : Quora rocks
author : Ross
tags : compute_instances : Array
0 : Object
label_name : value
1 : Object
label_name : value

我想让 0 命名为 test0 和 1 命名为 test1。 请指导我如何实现这一目标。

最好的问候

【问题讨论】:

    标签: python mongodb mongoengine


    【解决方案1】:

    尚不清楚您使用什么来打印对象,但这里有一些 cmets 可能会对您有所帮助:

    • 您的compute_instances_subtype 类没有设置title 字段,因此当您设置add_test0_label.title = "test0" 时,它只是添加到python 对象中,但在您调用.save() 时它不会保存在数据库中。李>
    • 您在输出中看到的 0 和 1 是 compute_instances 数组中 Object 的索引

    下面是一个可能也有帮助的简化示例:

    class ComputeInstancesSubtype(EmbeddedDocument):
        label_name = StringField()
        title = StringField()
    
    class Post(Document):
        title = StringField(max_length=120, required=True)
        compute_instances = ListField(EmbeddedDocumentField(ComputeInstancesSubtype))
    
    nested1 = ComputeInstancesSubtype(title='something0', label_name='test0')
    nested2 = ComputeInstancesSubtype(title='something1', label_name='test1')
    post = Post(title="Quora rocks", compute_instances = [nested1, nested2])
    post.save()
    
    print(Post._get_collection().find_one())    # print it in its raw format
    

    返回

    {'_id': ObjectId('61071c5e3686c4066dadbc05'),
     'title': 'Quora rocks',
     'compute_instances': [{'label_name': 'test0', 'title': 'something0'},
                          {'label_name': 'test1', 'title': 'something1'}]
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 2016-08-02
      • 2012-09-05
      相关资源
      最近更新 更多