You need to enable JavaScript to run this app. MongoDB使用$project查询时如何仅返回数组内的指定字段值
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB使用$project查询时如何仅返回数组内的指定字段值

解法说明

你原有写法的问题是仅保留了addresses数组内的country字段,没有将该字段提取到顶层,按照你的需求可以分场景选择以下实现方式:

场景1:输出所有地址的country组成的数组

期望输出格式:

{"country": ["US", "CA"]}

查询语句:

db.你的集合名.aggregate([
  {
    $project: {
      _id: 0,
      country: "$addresses.country"
    }
  }
])

场景2:仅输出第一个地址的country字符串值

期望输出格式:

{"country": "US"}

MongoDB 4.4及以上版本可直接用$first操作符:

db.你的集合名.aggregate([
  {
    $project: {
      _id: 0,
      country: { $first: "$addresses.country" }
    }
  }
])

低版本兼容写法,用$arrayElemAt指定取数组第0位元素:

db.你的集合名.aggregate([
  {
    $project: {
      _id: 0,
      country: { $arrayElemAt: [ "$addresses.country", 0 ] }
    }
  }
])

场景3:每个地址的country拆分为独立文档

期望输出格式:

{"country": "US"}
{"country": "CA"}

查询语句:

db.你的集合名.aggregate([
  { $unwind: "$addresses" },
  {
    $project: {
      _id: 0,
      country: "$addresses.country"
    }
  }
])

内容的提问来源于stack exchange,提问作者Sansli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 22:45:07