You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB三级嵌套数组元素组合有效性验证查询问题

数据库模式(DB Schema)
[{
  "_id": 1,
  "name": "city1",
  "districts": [
    {
      "id": 5,
      "name": "district 1",
      "neighborhoods": [
        {
          "id": 309,
          "name": "neighborhood 1"
        }
      ]
    },
    {
      "id": 6,
      "name": "district 2",
      "neighborhoods": [
        {
          "id": 52280,
          "name": "neighborhood 2"
        }
      ]
    }
},
{
  "_id": 1,
  "name": "city2",
  "districts": [
    {
      "id": 5,
      "name": "district 3",
      "neighborhoods": [
        {
          "id": 309,
          "name": "neighborhood 3"
        }
      ]
    },
    {
      "id": 6,
      "name": "district 4",
      "neighborhoods": [
        {
          "id": 52280,
          "name": "neighborhood 4"
        },
        {
          "id": 52287,
          "name": "neighborhood 5"
        }
      ]
    }
}]
需求目标

我需要验证城市(name)、区域(districts.name)、社区(districts.neighborhoods.name)的三元组组合是否有效,即三者是否存在正确的嵌套关系。

示例1

输入city1、district 1、neighborhood 1,属于有效组合(三者正确嵌套)

示例2

输入city2、district 4、neighborhood 4,属于有效组合

示例3

输入city1、district 1、neighborhood 2,不属于有效组合(三者无正确嵌套关系)

示例4

输入city1、district 3、neighborhood 3,不属于有效组合

期望输出

若输入有效组合(如city1、district 1、neighborhood 1),应返回对应嵌套结构:

{
  "_id": 1,
  "name": "city1",
  "districts": [
    {
      "id": 5,
      "name": "district 1",
      "neighborhoods": [
        {
          "id": 309,
          "name": "neighborhood 1"
        }
      ]
    }
}

若输入无效组合(如city1、district 1、neighborhood 2),应返回空、null或其他表示不存在的结果。

当前实现方案
doesLocationExist = await locationDbConnection.find_one(
        { "location" : {
            "$elemMatch" :  
                {"name" : city, "districts.name" : district, "districts.neighborhoods.name": neighborhood}
            }
        }
    )

预期该查询在组合有效时返回文档,但实际始终返回None。我需要通过三元组路径检索双层嵌套数组元素,以此验证组合有效性。

未解决问题的参考链接
  • Finding nested array mongodb
  • Extracting particular element in MongoDb in Nested Arrays
  • Find document with array that contains a specific value

注:区域和社区名称不唯一,因此无法使用投影仅显示目标数组元素。


内容的提问来源于stack exchange,提问作者Ahmet-Salman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:43:17