Home > Software design >  2 x criteria for Match showing no results
2 x criteria for Match showing no results

Time:05-14

I am trying to show results where the sum of records is greater or equal to 4 and the status matches a string. If I leave off the status field it works fine but adding it in always gives me an empty array even when there should be data.

const bookings = await Booking.aggregate([
    {
        $group: {
            _id: {
                $dateToString: {
                    format: "%Y/%m/%d",
                    date: "$bookingDate",
                },
            },
            totalBookings: {
                $sum: 1,
            },
        },
  },
    {
        $match: {
            totalBookings: {
                $gte: 4,
            },
            status: "Accepted",
        },
  },
]);

CodePudding user response:

Each booking will have it's own status. So you need to add that as part of $group

  {
    $group: {
      _id: {
        status: "$status",
        "d": {
          $dateToString: {
            format: "%Y/%m/%d",
            date: "$bookingDate",
            
          }
        },
        
      },
      totalBookings: {
        $sum: 1,
        
      },
      
    }
  }

Then you need to change your match as below

 $match: {
            totalBookings: {
                $gte: 4,
            },
            "_id.status": "Accepted",
        }

It will give you all the Accepted Booking on the given BookinDate which is >= 4.

  • Related