javascript - Sum Up for each element of Collection.find() -
i try sum specific column of datapoints collection fits specific query.
getclickstotalcampaign: function () { var docs = datapoints.find({campaign: this._id, influencer: meteor.userid()}); var clicks = 0; for(var = 0; i< docs.length; i++) { clicks += parseint(docs[i].clicks); } return clicks; },
i wrong return of datapoints.find beeing array of objects? length of null, when query on mongo entrys back. @edit here data schema:
schemas.datapoints = new simpleschema({ influencer: { type: string, label: "influencer id" }, advertiser: { type: string, label: "advertiser id" }, campaign: { type: string, label: "campaign id" }, amount: { type: number, label: "amount" } });
use aggregation framework can use $match
pipeline operator filter collection on campaign , influencer. $group
pipeline step groups input documents filter , applies accumulator expression $sum
group total documents count.
your pipeline this:
var datapoints = new mongo.collection('datapoints'); var pipeline = [ { "$match": { "campaign": this._id, "influencer": meteor.userid() } }, { "$group": { "_id": null, "count": {"$sum": "$amount"} } } ]; var result = datapoints.aggregate(pipeline).fetch(); var count = result[0].count;
you can add meteorhacks:aggregate package implement aggregation in meteor:
add app with
meteor add meteorhacks:aggregate
since package exposes .aggregate
method on mongo.collection instances, can call method result array document has count field. example
if (meteor.isserver) { var datapoints = new mongo.collection('datapoints'); meteor.methods({ getclickstotalcampaign: function () { var pipeline = [ { "$match": { "campaign": this._id, "influencer": meteor.userid() } }, { "$group": { "_id": null, "count": {"$sum": "$amount"} } } ]; var result = datapoints.aggregate(pipeline); return result[0].count; } }); } if (meteor.isclient) { setinterval(function () { meteor.call('getclickstotalcampaign', updatecounter); }, 1000 * 10); function updatecounter(err, count) { console.log("this new count: ", count) } }
Comments
Post a Comment