MongoDB聚合如何按自定义规则将checkins子数组合并为对象
你可以直接使用以下MongoDB聚合语句实现需求:
db.你的集合名.aggregate([ { $addFields: { checkin: { $switch: { branches: [ // 空数组返回null { case: { $eq: [{ $size: "$checkins" }, 0] }, then: null }, // 仅1个元素时直接返回该元素 { case: { $eq: [{ $size: "$checkins" }, 1] }, then: { $first: "$checkins" } } ], // 多个元素时合并首尾指定属性 default: { _id: { $first: "$checkins._id" }, in_at: { $first: "$checkins.in_at" }, out_at: { $last: "$checkins.out_at" } } } } } }, // 移除原checkins字段,输出符合要求的结构 { $project: { name: 1, checkin: 1, _id: 0 } } ])
如果你使用的MongoDB版本低于4.4,不支持直接对数组使用$first/$last运算符,可以用$arrayElemAt替换对应逻辑:
- 替换
$first: "$checkins"为{ $arrayElemAt: ["$checkins", 0] } - 替换
$first: "$checkins.xxx"为{ $arrayElemAt: ["$checkins.xxx", 0] } - 替换
$last: "$checkins.xxx"为{ $arrayElemAt: ["$checkins.xxx", -1] }
内容的提问来源于stack exchange,提问作者Scoopa
相关产品推荐
相关产品推荐

