You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:57:03