【发布时间】:2017-12-21 04:53:30
【问题描述】:
如何查询 MongoDB 文档中的特定对象并仅检索该对象
文档:
{
"_id" : "mac_table",
"00:50:56:84:c8:1b" : {
"switch_port" : "ethernet1/37",
"mac_ip_routed_by" : "or1-befw02",
"mac_switch" : "adsfasfd",
"mac_ip" : "ddsfa",
"switch_port_description" : "asdfsafsfda",
"mac_ip_dns" : "asdfsafd",
"switch_port_mode" : "trunk",
"mac_vlan:" : "3362"
},
"00:50:56:84:c8:1f" : {
"switch_port" : "ethernet1/13",
"mac_ip_routed_by" : "asdf",
"mac_switch" : "dfdsfd",
"mac_ip" : "asdfasdf",
"switch_port_description" : "adsfasdf",
"mac_ip_dns" : "asdfasfd",
"switch_port_mode" : "trunk",
"mac_vlan:" : "3201"
},
"00:50:56:a5:64:f0" : {
"switch_port" : "",
"mac_ip_routed_by" : "adsfdfsa",
"mac_switch" : "",
"mac_vlan" : "",
"mac_ip" : "adsfasdf",
"switch_port_description" : "",
"mac_ip_dns" : "adadfsadf",
"switch_port_mode" : "asdsadf"
},
"18:a9:05:65:43:12" : {
"switch_port" : "ethernet116/1/6",
"mac_ip_routed_by" : "nvvvvvv",
"mac_switch" : "aaana",
"mac_ip" : "10.40.77.60",
"switch_port_description" : "test",
"mac_ip_dns" : "test",
"switch_port_mode" : "access",
"mac_vlan:" : "76"
}
}
我只想检索:
"00:50:56:84:c8:1b" : {
"switch_port" : "ethernet1/37",
"mac_ip_routed_by" : "or1-befw02",
"mac_switch" : "adsfasfd",
"mac_ip" : "ddsfa",
"switch_port_description" : "asdfsafsfda",
"mac_ip_dns" : "asdfsafd",
"switch_port_mode" : "trunk",
"mac_vlan:" : "3362"
}
对于我尝试的每个查询,它都会返回整个文档,并且我在这个单个文档中有大约 30K 个对象。如果我的数据结构不正确,请告知如何更好地构建数据以获得我需要的查询。我担心添加 30K 文档与 1 个具有 30k 对象的文档。
【问题讨论】:
-
将文档改为键值对,可以通过key获取键值对。这将帮助您进行未来的查询和更新,并与 mongodb 数据库配合使用。像
{'_id:"mac_table", "kvp":[{"k":"00:50:56:84:c8:1b", "v":{"switch_port":...}}, other key value pairs]}这样的东西。要获取密钥的值,您可以使用db.collection_name.find({}, {"kvp":{"$elemMatch":{"k":"00:50:56:84:c8:1b"}}}) -
@veeram 同意,我以后可能会为此尝试修改它,谢谢。
标签: mongodb mongodb-query