如何从Mongoose的Map类型属性中提取指定字段生成数组
方案1:查询后在代码层面处理(最简便)
查询拿到文档对象后直接操作box字段即可:
// 示例:查询_id为1的MyCar文档 const targetCar = await MyCar.findOne({ _id: 1 }); // 提取所有box元素的name字段 const nameArray = Object.values(targetCar.box).map(boxItem => boxItem.name);
执行后nameArray就是你需要的["apple", "banana"]格式数组。
方案2:用MongoDB聚合管道直接在数据库层获取结果
不需要拿到全量文档,直接通过聚合操作返回目标数组:
const res = await MyCar.aggregate([ // 匹配目标文档,可根据你的查询条件修改 { $match: { _id: 1 } }, // 将Map类型的box字段转为[k,v]结构的数组 { $addFields: { boxList: { $objectToArray: "$box" } } }, // 遍历数组提取name字段 { $project: { _id: 0, nameList: { $map: { input: "$boxList", in: "$$this.v.name" } } }} ]); // 取结果集中的nameList即可 const nameArray = res[0]?.nameList || [];
注意事项
- 你提供的Schema中MyBox定义的数值字段为
value,但示例数据中使用的是price,实际开发时请和你的业务字段名保持一致,避免取值为空。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

