简体   繁体   English

当嵌套字典键发生变化时,如何使用嵌套字典查询 mongodb 文档?

[英]How can i query mongodb document with nested dictionaries, when the nested dictionary keys are changing?

I am using mongoengine to query and save data to my mongo database using ODM.我正在使用 mongoengine 使用 ODM 查询数据并将数据保存到我的 mongo 数据库。 i have a document with an attribute named interfaces which contains another dictionary as its value.我有一个名为 interfaces 的属性的文档,其中包含另一个字典作为其值。

example:例子:

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

Each document can have hundreds of interfaces under the interfaces attributes.每个文档在 interfaces 属性下可以有数百个接口。

I am looking for a way to test if '1.2.3.4' is under any of the interfaces of the document.我正在寻找一种方法来测试“1.2.3.4”是否在文档的任何接口下。

i found out using document.objects() and looping through all the records like so:我发现使用document.objects()并循环遍历所有记录,如下所示:

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

But eventually the collection will have 1000+ documents and this seems like such a slow solution.但最终该集合将有 1000 多个文档,这似乎是一个缓慢的解决方案。 Any way to query it directly from the mongodb?有什么办法可以直接从mongodb查询吗?

Thank you for any help!感谢您的任何帮助!

You can't.你不能。 The essence of mongodb is a key, value pair store. mongodb 的本质是键值对存储。 You can't look up the values without knowing the key.不知道密钥就无法查找值。

I suggest redesign you schema along these lines:我建议您按照以下方式重新设计架构:

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},
        .
        .
        .
    ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM