【问题标题】:MongoDB: How to get data of a nested object searching by a key value?MongoDB:如何通过键值搜索嵌套对象的数据?
【发布时间】:2020-05-13 18:46:02
【问题描述】:

我正在学习 MongoDB,并尝试使用 MongoDB 客户端按特定键值检索对象。

我有这些数据:

{
    "type": "products",
    "products": {
        "Intel® Core™ i9-9980XE Extreme Edition": {
            "description": null,
            "price": 2457,
            "catalog_id": "1"
        },
        "Intel® Core™ i9-9980HK": {
            "description": null,
            "price": 1548,
            "catalog_id": "1"
        },
        "AMD Ryzen Threadripper 2990WX": {
            "description": null,
            "price": 500,
            "catalog_id": "2"
        },
        "Baikalel Ectronics BE-M1000": {
            "description": null,
            "price": 128,
            "catalog_id": "3"
        },
        "GeForce RTX 2080 Ti": {
            "description": null,
            "price": 2048,
            "catalog_id": "5"
        }   
    }
}

我已经了解了如何访问嵌套对象中的数据:

db.shop.findOne( { type : "products" }).products["GeForce RTX 2080 Ti"].price

但我有点困惑如何让 "catalog_id": "1" 过滤所有 hested 对象

当我使用时

db.shop.find( { type : "products" }, {"catalog_id": "1"})

MongoDB 客户端只显示主对象的 id。

【问题讨论】:

    标签: json mongodb


    【解决方案1】:

    db.shop.find( { "products.catalog_id": "1"})

    类似问题MongoDB: How to find a document by an id inside a nested document

    【讨论】:

      【解决方案2】:

      您在此处共享的数据看起来只是一个对象,具有两个键类型和产品。因此,您的查询与该对象匹配并正确返回该对象。你需要在之后解析它。 Mongo 查询只会给你记录。

      {
          **"_id": ObjectId("58c7da2adaa8d031ea699fff")** 
          "type": "products",
          "products": {
              "Intel® Core™ i9-9980XE Extreme Edition": {
                  "description": null,
                  "price": 2457,
                  "catalog_id": "1"
              },
              "Intel® Core™ i9-9980HK": {
                  "description": null,
                  "price": 1548,
                  "catalog_id": "1"
              },
              "AMD Ryzen Threadripper 2990WX": {
                  "description": null,
                  "price": 500,
                  "catalog_id": "2"
              },
              "Baikalel Ectronics BE-M1000": {
                  "description": null,
                  "price": 128,
                  "catalog_id": "3"
              },
              "GeForce RTX 2080 Ti": {
                  "description": null,
                  "price": 2048,
                  "catalog_id": "5"
              }   
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-16
        • 1970-01-01
        • 2021-11-30
        • 1970-01-01
        • 1970-01-01
        • 2018-09-10
        • 2017-01-28
        • 2018-01-30
        • 2014-10-22
        相关资源
        最近更新 更多