【问题标题】:How can i query mongodb document with nested dictionaries, when the nested dictionary keys are changing?当嵌套字典键发生变化时,如何使用嵌套字典查询 mongodb 文档?
【发布时间】:2020-12-15 01:31:59
【问题描述】:

我正在使用 mongoengine 使用 ODM 查询数据并将数据保存到我的 mongo 数据库。 我有一个文档,其属性名为 interfaces,其中包含另一个字典作为其值。

示例:

attr1: value
attr2: value
interfaces:
    {
        interface1: {'ip': 1.2.3.4, test:test2}
        interface2: {'ip': 2.3.4.5, test:test3}
        .
        .
        .
    }

每个文档在interfaces属性下可以有数百个接口。

我正在寻找一种方法来测试“1.2.3.4”是否在文档的任何接口下。

我发现使用document.objects() 并像这样遍历所有记录:

records = document.objects()
for key in records.interfaces.keys():
    if records.interfaces[key]['ip'] == “1.2.3.4”:
        dosomething

但最终该集合将包含 1000 多个文档,这似乎是一个缓慢的解决方案。 有什么方法可以直接从 mongodb 查询?

感谢您的帮助!

【问题讨论】:

    标签: python database mongodb pymongo mongoengine


    【解决方案1】:

    你不能。 mongodb的本质是键值对存储。不知道键就无法查找值。

    我建议您按照以下思路重新设计架构:

    attr1: value
    attr2: value
    interfaces:
        [
            {'interface_number': 1, 'ip': 1.2.3.4, test:test2},
            {'interface_number': 2, 'ip': 2.3.4.5, test:test3},
            .
            .
            .
        ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      相关资源
      最近更新 更多