Unwind array of array in mongoDB

I have 2 tables booking and parking. In the booking table there is parkingId which refers to parking model. In the parking model there is a field named availability which is following:

[
    {
      "day": "Monday",
      "startTime": "09:00",
      "endTime": "17:00",
    },
    {... //Other days}
]

I want to unwind the availability array.

I have tried this:

let startTime = await Booking.aggregate([
      {
        $match: { _id: new mongoose.Types.ObjectId(req.params.id) },
      },
      {
        $lookup: {
          from: "parkings",
          localField: "parkingId",
          foreignField: "_id",
          as: "parking",
        },
      },
      {
        $unwind: "$parking",
      },
      { $unwind: "$parking.availability" },
    ]);

But it logs the result 6 times because there are 6 objects in the availability array like following.

[{
    _id: new ObjectId("62e8ac3943a6bfaf80de75b5"),
    parkingId: new ObjectId("62e11ab3079daa939290fa07"),
    user: new ObjectId("62c950dfc96c2b690028be88"),
    date: 2022-07-26T00:00:00.000Z,
    startTime: 2022-07-26T09:30:00.000Z,
    duration: { days: 0, hours: 2, minutes: 0 },
    endTime: 2022-07-26T11:30:00.000Z,
    isFeePaid: false,
    status: 'sent',
    isBookingCancelled: { value: false },
    isStarted: false,
    isEnabled: false,
    parking: {
      _id: new ObjectId("62e11ab3079daa939290fa07"),
      userId: new ObjectId("62c950dfc96c2b690028be88"),
      contactInfo: [Object],
      about: 'Nisi occaecat ipsum',
      parkingImage: [],
      location: [Array],
      price: 5,
      availability: [Object],
      parkingType: 'residence',
      parkingInfo: [Array],
      totalSpots: 10,
      coordinates: [Object],
      status: 'active',
      isFeePaid: false,
    }
  },
]

I want only availability of the requested day only. How can I get this?

You need a $set stage that uses $filter on the array.

1 Like