我正在执行包含许多数据库操作的集成任务,并且一切顺利,直到无法过滤文档中的嵌入式文档。
我的文档看起来像
{
flightId: "IND-101",
AircraftName: "Delta Airlines",
fare: 600,
availableSeats: 5,
status: "Running",
bookings: [
{
customerId: "P1001",
bookingId: 2001,
noOfTickets: 3,
bookingCost: 1800
},
{
customerId: "S1001",
bookingId: 2003,
noOfTickets: 2,
bookingCost: 1200
}
]
},
{
flightId: "IND-102",
AircraftName: "JetBlue",
fare: 750,
availableSeats: 20,
status: "Cancelled",
bookings: [
{
customerId: "P1001",
bookingId: 2002,
noOfTickets: 3,
bookingCost: 2250
},
{
customerId: "G1001",
bookingId: 2004,
noOfTickets: 2,
bookingCost: 1500
}
]
}
我尝试了以下代码,但显然,它正在返回所有预订文件。
return flightModel.find({ $and: [{ flightId: flightId }, { "bookings.customerId": customerId }] }, { bookings:1, _id: 0 })
使用函数给定变量flightId和customerId。 如果我将flightId指定为IND-101,将customerID指定为P1001,则所需的输出为
{
customerId: "P1001",
bookingId: 2001,
noOfTickets: 3,
bookingCost: 1800
}
那我该怎么做呢?如何根据过滤条件选择特定的嵌入式文档?
答案 0 :(得分:1)
您可以对$filter
和$project
所需的字段运行汇总查询。
这样的事情应该起作用。
let pipeline = [
{$match: {flightId: flightId}},
{$filter: {
input: '$bookings'
as: 'booking',
cond: {$eq: {'$$booking.customerId', customerId}}
}},
{$project: {
bookings: "$bookings"
}}
]
flightModel.aggregate(pipeline);