So I have a schema, and in that schema there is an object called "caseCount" with a Number Value. I simply want to fetch every value for each object of "caseCount" and add it up. Could somebody point me in the right direction? If I need to explain some more, I'm happy to do so. Thank you!
Schema:
const Profile = Schema({
userID: String,
messageCount: Number,
caseCount: Number,
Skins: Array,
});
code:
const data = Profiles.collection.aggregate([{
$group: {
_id: '$id',
totalCaseCount: { $sum: '$caseCount' }
}
}]);
Demo - https://mongoplayground.net/p/7TnpQl3tJHt
Use $sum in aggregation query.
db.collection.aggregate({
$group: {
_id: null,
toatalCaseCount: { $sum: "$caseCount" }
}
})
Profiles.collection.aggregate([{
$group: {
_id: null,
totalCaseCount: { $sum: '$caseCount' }
}
}], function(err, data) {
console.log(data); // here you'll get your data from the query
});