MongoDB聚合优化:单管道获取数组指定条件的字段值
解决方案:MongoDB聚合查询获取数组中指定条件元素的字段值
适配MongoDB 4.4+的简洁写法
db.collection.aggregate([ { $match: { _id: 1 } }, { $project: { indexValue: { $getField: { field: "z", input: { $first: { $filter: { input: "$items", cond: { $eq: ["$$this.y", "five"] } } } } } } } } ])
兼容低版本MongoDB的写法
如果你的MongoDB版本低于4.4(不支持$getField和$first),可以用以下写法:
db.collection.aggregate([ { $match: { _id: 1 } }, { $project: { indexValue: { $arrayElemAt: [ { $map: { input: { $filter: { input: "$items", cond: { $eq: ["$$this.y", "five"] } } }, as: "matchedItem", in: "$$matchedItem.z" } }, 0 ] } } } ])
方案解析
- 动态筛选元素:使用
$filter遍历items数组,根据y: "five"的条件筛选目标元素,彻底摆脱对固定数组索引的依赖 - 提取目标字段:通过
$first(或$arrayElemAt)获取筛选结果中的第一个匹配元素,再直接提取其z字段值 - 优化性能:仅用单个
$project阶段完成字段转换,减少管道阶段的运算开销,提升查询效率
内容的提问来源于stack exchange,提问作者Jalpen Bhatt
相关产品推荐
相关产品推荐

