我尝试总结适合特定查询的数据点集合的特定列。
getClicksTotalCampaign: function () {
var docs = DataPoints.find({campaign: this._id, influencer: Meteor.userId()});
var clicks = 0;
for(var i = 0; i< docs.length; i++) {
clicks += parseInt(docs[i].clicks);
}
return clicks;
},
我对 DataPoints.find 的返回是一个对象数组有误吗?它的长度始终为空,当我在 mongo 上进行查询时,我得到了条目。 @edit这里是数据架构:
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"
}
});
最佳答案
使用aggregation framework 您可以在其中使用 $match
管道运算符,用于过滤事件和影响者的集合。 $group
管道步骤然后对过滤器中的所有输入文档进行分组并应用累加器表达式 $sum
到组中获取文档总数。
您的管道将如下所示:
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;
您可以添加meteorhacks:aggregate package 在 Meteor 中实现聚合:
添加到您的应用
meteor add meteorhacks:aggregate
由于此包在 Mongo.Collection 实例上公开了 .aggregate
方法,因此您可以调用该方法来获取具有 count 字段的文档的结果数组。例如
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 is the new count: ", count)
}
}
关于javascript - 对 Collection.find() 的每个元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31232527/