Created
May 23, 2022 20:02
-
-
Save sourabhbagrecha/f12fdd5cb5816b541f0412e988d1d64d to your computer and use it in GitHub Desktop.
This file contains 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
exports = async (input) => { | |
// fetching the from and to date from the input query of Custom GraphQL Resolver | |
const {from, to} = input; | |
const collection = context.services.get('mongodb-atlas').db('expengo').collection("expenses"); | |
const user = context.user.id; | |
// Creating a pipeline that matches the current author and the timeline mentioned in the input query, | |
// and then combine all the amount by category. | |
const pipeline = [ | |
{ | |
$match: { | |
author: new BSON.ObjectId(user), | |
createdAt: {$gte: new Date(from), $lte: new Date(to)} | |
} | |
}, | |
{ | |
$group: { | |
_id: "$category", | |
amount: {$sum: "$amount"} | |
} | |
}, | |
{ | |
$project: { | |
category: "$_id", | |
amount: 1, | |
_id: 0 | |
} | |
} | |
]; | |
const categories = await collection.aggregate(pipeline).toArray(); | |
return { categories }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment