【问题标题】:Query Specific Object Inside MongoDB Document And Retrieve Only That Object查询 MongoDB 文档中的特定对象并仅检索该对象
【发布时间】: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


【解决方案1】:

您应该可以像这样简单地使用projection

db.collection.find({}, { "00:50:56:84:c8:1b": 1 })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    相关资源
    最近更新 更多