MongoDB聚合如何合并$facet输出的roomInfo与hotelInfo并过滤满房酒店
MongoDB聚合管道实现方案
你可以在$facet阶段之后追加以下聚合阶段完成需求:
完整管道代码
[ // 阶段1:将roomInfo转为_id到booked的映射字典,提升匹配效率 { $set: { roomBookingMap: { $arrayToObject: { $map: { input: "$roomInfo", in: { k: "$$this._id", v: "$$this.booked" } } } } } }, // 阶段2:为所有房间填充booked字段,未匹配默认赋值0 { $set: { hotelInfo: { $map: { input: "$hotelInfo", as: "hotel", in: { name: "$$hotel.name", roomDetails: { $map: { input: "$$hotel.roomDetails", as: "room", in: { _id: "$$room._id", roomCount: "$$room.roomCount", booked: { $ifNull: [{$getField: {input: "$roomBookingMap", field: "$$room._id"}}, 0] } } } } } } } } }, // 阶段3:过滤满房酒店,仅保留存在可售房间的酒店 { $set: { hotelInfo: { $filter: { input: "$hotelInfo", as: "hotel", cond: { $anyElementTrue: { $map: { input: "$$hotel.roomDetails", in: {$gt: ["$$this.roomCount", "$$this.booked"]} } } } } } } }, // 阶段4:将酒店数组拆分为独立文档,为分页做准备 {$unwind: "$hotelInfo"}, // 阶段5:将酒店数据提为根文档,得到预期输出结构 { $replaceRoot: {newRoot: "$hotelInfo"} } // 后续可直接追加 $skip、$limit 阶段实现分页 ]
低版本兼容说明
如果你的MongoDB版本低于5.0(不支持$getField操作符),可以将阶段2中booked字段的赋值逻辑替换为如下写法:
booked: { $let: { vars: { match: { $first: { $filter: { input: "$roomInfo", cond: {$eq: ["$$this._id", "$$room._id"]} } } } }, in: {$ifNull: ["$$match.booked", 0]} } }
内容的提问来源于stack exchange,提问作者Mahtab Hossain
相关产品推荐
相关产品推荐

