如何使用MongoDB的aggregate与lookup从对象数组中获取最小unit_price值
问题原因
你现有写法的核心问题有两个:
$group阶段仅保留了分组id和最小值计算结果,直接丢失了property表的原始字段、以及完整的property_prices关联列表- 你的
unit_price字段同时存在数字和字符串两种类型,直接计算最小值会出现类型匹配异常,得到错误结果
正确实现代码
await Property.aggregate([ // 可选:如果只查询property_id为1的记录,提前过滤减少计算量 { $match: { _id: "1" } }, { $lookup: { from: 'property_prices', as: 'property_prices', let: { property_id: '$_id' }, pipeline: [ { $match: { $expr: { $and: [ { $eq: ['$property_id', '$$property_id'] }, { $eq: ['$status', 'Completed'] } ] } } } ] } }, // 新增字段计算全局最小unit_price { $addFields: { minInvestment: { $min: { $reduce: { // 遍历所有关联的价格记录 input: "$property_prices", initialValue: [], in: { $concatArrays: [ "$$value", // 展开单条价格记录里的所有monthly_unit_price的unit_price,统一转成数字 { $map: { input: "$$this.monthly_unit_price", in: { $toDouble: "$$this.unit_price" } } } ] } } } } } } ])
实现说明
$reduce会遍历所有关联的property_prices记录,把每条记录里的monthly_unit_price数组中的unit_price全部提取出来,统一转成Double类型后拼接成一个一维数组$min直接计算这个一维数组的最小值,就是当前property对应的全局最低单价- 保留了property表的所有原始字段,以及完整的
property_prices关联列表,完全符合你需要的返回格式
内容的提问来源于stack exchange,提问作者abhiburk
相关产品推荐
相关产品推荐

