Home > Net >  Show only records with count greater than certain number using aggregation
Show only records with count greater than certain number using aggregation

Time:05-11

I am trying to only show the records which have a sum greater than or equal to four. This isn't working.

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

CodePudding user response:

db.collection.aggregate([
  {
    $group: {
      _id: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: "$bookingDate",
          
        },
        
      },
      totalBookings: {
        $sum: 1,
        
      },
      
    }
  },
  {
    $match: {
      totalBookings: {
        $gte: 4,
        
      },
      
    },
    
  },
  
])

There is a mismatch. Your key is totalBookings but not sum

EDIT:

Refer this

  • Related