mongoose sum a value across all documents mongoose sum a value across all documents mongodb mongodb

mongoose sum a value across all documents


Try it with the aggregation framework using the $match and $group operators, i.e. something like this

db.tickets.aggregate([    { $match: { time: {$gte: a, $lte: tomorrow} } },    { $group: { _id: null, amount: { $sum: "$amount" } } }])

for example with test data like this

/* 1 */{    "_id" : ObjectId("57e0ed40828913a99c2ceb46"),    "time" : 20,    "amount" : 40}/* 2 */{    "_id" : ObjectId("57e0ed40828913a99c2ceb47"),    "time" : 40,    "amount" : 20}/* 3 */{    "_id" : ObjectId("57e0ed40828913a99c2ceb48"),    "time" : 50,    "amount" : 10}/* 4 */{    "_id" : ObjectId("57e0ed40828913a99c2ceb49"),    "time" : 10,    "amount" : 5}

a pipeline (with dummy time range) like the following

db.tickets.aggregate([    { $match: { time: {$gte: 20, $lte: 40} } },    { $group: { _id: null, amount: { $sum: "$amount" } } }])

would give you a result like this

/* 1 */{    "_id" : null,    "amount" : 60}

Pipeline in action