Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can sum all the values of a property in a Meteor collection?

For example :

Object {_id: "9g9ySxozSWn1", name: "test1", price: 1}
Object {_id: "9g9ySxozSWn2", name: "test2", price: 2}
Object {_id: "9g9ySxozSWn3", name: "test3", price: 3}
Object {_id: "9g9ySxozSWn4", name: "test3", price: 6}
Object {_id: "9g9ySxozSWn5", name: "test3", price: 3}

What is the best way to sum up all the price where for example the name is test3?

like image 448
moni Avatar asked Dec 02 '22 23:12

moni


2 Answers

if you don't want to use Underscore:

var total = 0;

MyCollection.find({name:"test3"}).map(function(doc) {
  total += doc.price;
});
like image 111
travellingprog Avatar answered Dec 15 '22 00:12

travellingprog


Is this on the client? At the moment aggregation queries aren't yet directly supported, minimongo even with an aggregation query would still do a localized map-reduce in one way or another:

total = _.reduce(_.map(MyCollection.find({name:"test3"}).fetch(), 
                function(doc) {
                  //map
                  return doc.price
                }), 
                function(memo, num){ 
                  //reduce
                  return memo + num;
                });
like image 30
Tarang Avatar answered Dec 14 '22 22:12

Tarang