javascript - 对 Collection.find() 的每个元素求和

标签 javascript mongodb meteor

我尝试总结适合特定查询的数据点集合的特定列。

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/

相关文章:

javascript - 将字段与 id 匹配并插入数据 - meteor

node.js - Azure MongoDB find操作查询时间很慢

node.js - Mongoose 在对象展开字段上的聚合查找不起作用

javascript - 为什么 regex 或 .replace() 不使用 CKEditor 和 Javascript 替换脚本中的字符串?

javascript - 通过 PHP 或 Java 显示 HTML 源代码

mongodb - 更新 mongodb 中的子对象

meteor - Meteor 中是否有 'private' 服务器方法?

javascript - meteor 句柄表单输入

javascript - 访问对象中的函数,嵌套在另一个函数中

javascript - 通过ajax调用多个脚本。脚本 2 应仅在脚本 1 执行完毕后调用