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
相关产品推荐
相关产品推荐

