MongoDB/Mongoose使用$elemMatch提取嵌套数组指定字段的方法
解决方案
你当前使用的$elemMatch仅支持筛选数组中符合条件的元素,无法对匹配到的元素内部字段进行裁剪,需要使用聚合管道实现需求,原生MongoDB查询语句如下:
db.collection.aggregate([ // 文档级过滤条件,查询所有文档可省略该阶段 { $match: {} }, { $project: { totalScore: 1, monthly: { $map: { input: { $filter: { input: "$monthly", cond: { $and: [ { $eq: ["$$this.year", 2021] }, { $eq: ["$$this.month", 8] } ] } } }, in: { score: "$$this.score" } } } } } ])
如果使用Mongoose,对应写法如下:
Model.aggregate([ { $project: { totalScore: 1, monthly: { $map: { input: { $filter: { input: "$monthly", cond: { $and: [ { $eq: ["$$this.year", 2021] }, { $eq: ["$$this.month", 8] } ] } } }, in: { score: "$$this.score" } } } } } ]).exec((err, result) => { // 处理返回结果 })
上述语句会先过滤monthly数组中符合年月条件的元素,再对匹配到的元素做字段裁剪,仅保留score字段,最终返回结果和你预期的结构完全一致。
内容的提问来源于stack exchange,提问作者Chique
相关产品推荐
相关产品推荐

