moni
moni

Reputation: 201

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?

Upvotes: 4

Views: 5681

Answers (2)

travellingprog
travellingprog

Reputation: 1189

if you don't want to use Underscore:

var total = 0;

MyCollection.find({name:"test3"}).map(function(doc) {
  total += doc.price;
});

Upvotes: 15

Tarang
Tarang

Reputation: 75945

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;
                });

Upvotes: 2

Related Questions