如何在Meteor集合中对一个属性的所有值求和?

4
例如:
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}

如何最好地总结所有价格,例如名称为 test3?

2个回答

15

如果您不想使用Underscore:

var total = 0;

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

我喜欢这个!谢谢! - Julien Le Coupanec
两件事情:1)Meteor的.find()返回一个游标,所以最好像Akshat的答案一样做.find().fetch()。2)这是对map的误用,最好使用forEach。或者更好的方法是:total = MyCollect.find({ name: 'test3' }).fetch().map(item => item.price).reduce((a, b) => a + b) - ffxsam
是的,我很久以前写了这个答案,当时Meteor还非常不稳定。如果我没记错的话,我使用了map(),因为当时游标还没有forEach(),或者可能我只是一个函数式编程的新手哈哈。 - travellingprog

2

这是在客户端上吗?目前,聚合查询尚未直接支持,即使使用聚合查询,minimongo仍会以某种方式执行本地化的map-reduce:

total = _.reduce(_.map(MyCollection.find({name:"test3"}).fetch(), 
                function(doc) {
                  //map
                  return doc.price
                }), 
                function(memo, num){ 
                  //reduce
                  return memo + num;
                });

谢谢。请注意,reduce函数需要一个memo的初始值,你可以将其作为最后一个参数提供(例如...return memo+num; }, 0);)。详情请参见http://underscorejs.org/#reduce。 - Racing Tadpole

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接