Created
November 1, 2025 09:45
-
-
Save p-lurd/e8283b01241346e9d78a00f0b586bf1b to your computer and use it in GitHub Desktop.
One of the aggregation query I used
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| async findMany(id: string) { | |
| try { | |
| const data = await Model.aggregate([ | |
| { $match: { businessId: new mongoose.Types.ObjectId(id) } }, | |
| { $addFields: { | |
| dateString: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } } | |
| } | |
| }, | |
| { $sort: { createdAt: -1 } }, | |
| { $group: { | |
| _id: { | |
| apiId: "$apiId", | |
| date: "$dateString", | |
| success: "$success" | |
| }, | |
| firstResponse: { $first: "$$ROOT" } | |
| } | |
| }, | |
| { $group: { | |
| _id: { | |
| apiId: "$_id.apiId", | |
| date: "$_id.date" | |
| }, | |
| dayResponses: { $push: "$firstResponse" } | |
| } | |
| }, | |
| { $project: { | |
| _id: 0, | |
| apiId: "$_id.apiId", | |
| date: "$_id.date", | |
| selectedResponse: { | |
| $cond: [ | |
| { $eq: ["$_id.date", { $dateToString: { format: "%Y-%m-%d", date: new Date() } }] }, | |
| { $arrayElemAt: [{ $sortArray: { input: "$dayResponses", sortBy: { createdAt: -1 } } }, 0] }, | |
| { $arrayElemAt: [{ $sortArray: { input: "$dayResponses", sortBy: { success: 1, createdAt: -1 } } }, 0] } | |
| ] | |
| } | |
| } | |
| }, | |
| { $sort: { date: 1 } }, | |
| { $group: { | |
| _id: "$apiId", | |
| responses: { $push: "$selectedResponse" } | |
| } | |
| }, | |
| { $project: { | |
| _id: 1, | |
| responses: { $slice: ["$responses", 0, 30] } | |
| } | |
| } | |
| ]); | |
| return data; | |
| } catch (error) { | |
| if(error instanceof HttpException) { | |
| throw error; | |
| } | |
| throw new InternalServerErrorException(error.message); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment