MongoDB嵌套数组查询:仅返回匹配子文档及父级字段
MongoDB 嵌套数组仅返回匹配元素及父级字段的解决方案
你的原查询用find配合$投影没法实现需求,因为$投影只能定位到单层数组的第一个匹配元素,没法过滤第二层嵌套的cities数组里的元素。要精准返回指定城市及父级字段,得用聚合管道来处理,具体实现如下:
聚合查询代码
db.countries.aggregate([ // 筛选包含目标城市的文档,减少后续处理量 { $match: { "states.cities.name": "Kusugal" } }, // 展开states数组,单独处理每个州的城市列表 { $unwind: "$states" }, // 过滤当前州下匹配的城市,仅保留符合条件的元素 { $project: { _id: 1, name: 1, iso_code: 1, "states.name": 1, "states.cities": { $filter: { input: "$states.cities", cond: { $eq: ["$$this.name", "Kusugal"] } } } } }, // 过滤掉没有匹配城市的州,避免空数组结果 { $match: { "states.cities": { $ne: [] } } }, // 重新组合states数组,恢复原文档结构 { $group: { _id: "$_id", name: { $first: "$name" }, iso_code: { $first: "$iso_code" }, states: { $push: "$states" } } } ])
代码说明
- $match:先锁定包含目标城市的国家文档,减少无效数据处理。
- $unwind:拆分
states数组为单个文档,便于逐个处理每个州的城市列表。 - $project:通过
$filter遍历cities数组,只保留名称为"Kusugal"的城市。 - $match:剔除筛选后
cities为空的州,保证结果里的州都包含目标城市。 - $group:把拆分后的单个州文档重新聚合为数组,同时保留顶层字段,还原文档结构。
执行结果
运行上述查询后,会得到你期望的输出:
{ _id: ObjectId("634b08f7eb5cb6af473e3ab2"), name: 'India', iso_code: 'IN', states: [ { name: 'Karnataka', cities: [ { name: 'Kusugal', pincode: 580023, location: { type: 'point', coordinates: [Array] } } ] } ] }
内容的提问来源于stack exchange,提问作者Channaveer Hakari
相关产品推荐
相关产品推荐

