Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sourabhbagrecha/f12fdd5cb5816b541f0412e988d1d64d to your computer and use it in GitHub Desktop.
Save sourabhbagrecha/f12fdd5cb5816b541f0412e988d1d64d to your computer and use it in GitHub Desktop.
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