You need to enable JavaScript to run this app. MongoDB如何查询文档内嵌对象中符合过滤条件的键值对
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB如何查询文档内嵌对象中符合过滤条件的键值对

这个查询需求完全可以实现,通过MongoDB的聚合查询框架即可完成,以下是两种常用的实现方案:

方案1:使用$filter过滤(推荐,MongoDB 3.2+支持)

这种方案不需要展开数组,性能更高,适合数据量较大的场景:
查询代码如下:

db.你的集合名称.aggregate([
  // 第一步:匹配包含目标省份的文档,缩小查询范围
  {
    $match: {
      "country.states.data.state_name": "maharashtra"
    }
  },
  // 第二步:过滤数组仅保留匹配项,投影为期望格式
  {
    $project: {
      _id: 0,
      // 若要返回states为键的格式,将下面的key改成states即可
      state: {
        $first: {
          $filter: {
            input: "$country.states.data",
            cond: { $eq: ["$$this.state_name", "maharashtra"] }
          }
        }
      }
    }
  }
])

返回结果示例:

{
  "state": {
    "state_name": "maharashtra",
    "state_capital": "Mumbai"
  }
}

方案2:使用$unwind展开数组(兼容更低版本MongoDB)

如果使用的MongoDB版本不支持$first操作符,可以用数组展开再匹配的方式实现:
查询代码如下:

db.你的集合名称.aggregate([
  {
    $match: {
      "country.states.data.state_name": "maharashtra"
    }
  },
  // 展开states下的data数组
  { $unwind: "$country.states.data" },
  // 二次匹配仅保留符合条件的元素
  {
    $match: {
      "country.states.data.state_name": "maharashtra"
    }
  },
  // 投影为期望的格式
  {
    $project: {
      _id: 0,
      states: "$country.states.data"
    }
  }
])

返回结果示例:

{
  "states": {
    "state_name": "maharashtra",
    "state_capital": "Mumbai"
  }
}

内容的提问来源于stack exchange,提问作者Jerin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 18:45:05