Reputation: 643
I have this mongodb collection
{
"_id": "5ab93bd8bca5b3568ad93bc6",
"name": "abc",
"id":"1",
"price": 300000,
"__v": 0
}
{
"_id": "5ab9d8bca5b334328ad934c1",
"name": "cde",
"id":"1",
"price": 200000,
"__v": 0
}
I want to write a query to get the sum of the prices from all the documents from the collection. How could I do that?
Please use this route format. Regards
router.get('/values/:id', (req, res, next)=>{
Value.count({ id: req.params.id }, function(err, value){
res.json(value);
});
});
Upvotes: 0
Views: 139
Reputation: 6766
I want to right a query to get the sum of price from all the documents from the collection
So why does your route require an ID?
Anyways, use aggregation particularly $sum.
router.get('/values/:id', (req, res, next) => {
Value.aggregate([
{
$match: { id: req.params.id }
},
{
$group: {
_id: "id",
total: { $sum: "$price" }
}
}
], function (err, value){
console.log(value);
});
});
Upvotes: 1