gpt4 book ai didi

javascript - 如何过滤文档中的嵌入文档?

转载 作者:行者123 更新时间:2023-12-02 23:53:57 24 4
gpt4 key购买 nike

我正在做一项包含大量数据库操作的集成作业,一切顺利,直到我在过滤文档中的嵌入文档时遇到问题。

我的文档看起来像

{
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
}

那么我该怎么做呢?如何根据过滤条件选择特定的嵌入文档?

最佳答案

您可以对 $filter$project 所需的字段运行聚合查询。像这样的东西应该有效。

let pipeline = [
{$match: {flightId: flightId}},
{$filter: {
input: '$bookings'
as: 'booking',
cond: {$eq: {'$$booking.customerId', customerId}}
}},
{$project: {
bookings: "$bookings"
}}
]

flightModel.aggregate(pipeline);

关于javascript - 如何过滤文档中的嵌入文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55497673/

24 4 0