首页 > 解决方案 > 如何在mongodb的嵌套文档中查找记录

问题描述

这是 my_list 集合的示例记录,其中包含多级嵌套文档,如何从包含 3rd_party_setting 子记录和 with 的记录中找到对应的“key”值3rd_party_id="123456"?即找到对应的键值3rd_party_setting.3rd_party_id ="123456"

[
  {
    "_id": 551,
    "name": "demo1",
    "groups": {
      "123": {
        "name": "group1",
        "teams": {
          "110": {
            "name": "team1",
            "team_id": "2322"
          },
          "111": {
            "name": "team1",
            "team_id": "2322"
          }
        },
        "3rd_party_setting": {
          "3rd_party_id": "123456",
          "key": "this is the key",
          "create_dt": "2020-02-06 01:27:19",
          "update_dt": "2020-02-06 01:27:19"
        }
      }
    }
  },
  {
    "_id": 552,
    "name": "demo2",
    "groups": {
      "124": {
        "name": "group2",
        "teams": {
          "210": {
            "name": "team1",
            "team_id": "2322"
          },
          "211": {
            "name": "team1",
            "team_id": "2322"
          }
        },
        "3rd_party_setting": {
          "3rd_party_id": "123458",
          "key": "this is the key2",
          "create_dt": "2020-02-06 01:27:19",
          "update_dt": "2020-02-06 01:27:19"
        }
      }
    }
  },
  {
    "_id": 555,
    "name": "demo3",
    "groups": {
      "125": {
        "name": "group3",
        "teams": {
          "310": {
            "name": "team3",
            "team_id": "2322"
          },
          "311": {
            "name": "team3",
            "team_id": "2322"
          }
        }
      }
    }
  }
]

标签: mongodbmongodb-queryaggregation-framework

解决方案


您可以使用聚合获得您正在查看的内容。

这个聚合管道:

db.collection.aggregate([
  {
    $project: {
      o: {
        $objectToArray: "$groups"
      }
    }
  },
  {
    $match: {
      "o.v.3rd_party_setting.3rd_party_id": "123456"
    }
  },
  {
    $project: {
      key: "$o.v.3rd_party_setting.key"
    }
  }
])
  1. 在字段上使用 $objectToArray 将groups其拆分为kv检查内容,而不管键名如何
  2. 3rd_party_id 上的 $match
  3. $project 只返回所需的密钥

如果您有超过 1 个组的任何文档,您可能需要在匹配之前 $unwind。

样品操场


推荐阅读