MongoDB使用$addFields提取嵌套数组指定fieldName对应值并排序的问题
实现步骤
原有写法问题
- 字段路径错误:数据结构中
sections下嵌套的字段为fields,不是你写的fieldData - 过滤条件错误:匹配逻辑写为
$eq: ["$$this.fieldName", true],无法匹配到值为Author的fieldName - 结果提取缺失:
$filter返回的是数组,你没有提取数组元素的fieldValue属性,无法得到最终的字符串值
正确聚合写法
首先通过$reduce扁平化嵌套的字段数组,再过滤匹配指定字段名,最后提取对应值:
.addFields({ author: { $let: { vars: { // 把所有sections下的fields数组合并为一维数组 allFields: { $reduce: { input: "$sections", initialValue: [], in: { $concatArrays: ["$$value", "$$this.fields"] } } } }, in: { // 过滤出Author字段后提取fieldValue $getField: { field: "fieldValue", input: { $first: { $filter: { input: "$$allFields", cond: { $eq: ["$$this.fieldName", "Author"] } } } } } } } } })
如果使用的MongoDB版本低于5.0不支持$getField操作符,可以用如下兼容写法:
.addFields({ author: { $let: { vars: { allFields: { $reduce: { input: "$sections", initialValue: [], in: { $concatArrays: ["$$value", "$$this.fields"] } } }, matchedAuthor: { $first: { $filter: { input: "$$allFields", cond: { $eq: ["$$this.fieldName", "Author"] } } } } }, in: "$$matchedAuthor.fieldValue" } } })
排序实现
新增字段后追加$sort阶段即可按作者名称排序:
// 1为升序,-1为降序 .sort({ author: 1 })
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

