Vivek
Vivek

Reputation: 75

How can I filter embedded documents within a document?

I was doing an integrated assignment consisting a lot of database operations and I was going okay until I had trouble filtering embedded documents within a documents.

My document looks like

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

I have tried the below code but obviously, it is returning all the booking documents.

return flightModel.find({ $and: [{ flightId: flightId }, { "bookings.customerId": customerId }] }, { bookings:1, _id: 0 })

The variables flightId and customerId are given using a function. If I give flightId as IND-101 and customerID as P1001, then the desired output is

{
        customerId: "P1001",
        bookingId: 2001,
        noOfTickets: 3,
        bookingCost: 1800
    }

So how can I do this? How can I select a particular embedded document based on a filtering condition?

Upvotes: 0

Views: 47

Answers (1)

Isaac Vidrine
Isaac Vidrine

Reputation: 1666

You can run an aggregate query to $filter and $project the fields you need. Something like this should work.

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

flightModel.aggregate(pipeline);

Upvotes: 1

Related Questions