![](/img/trans.png)
[英]Complex collection.find() query and render it using {{#each collection}}
[英]Sum Up for each element of Collection.find()
我嘗試總結適合特定查詢的 DataPoints 集合的特定列。
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 beeing an Array of Objects 的返回有誤? 它的長度始終為空,當我在 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"
}
});
使用聚合框架,您可以在其中使用$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 包來實現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)
}
}
嘗試這個:
var docs = DataPoints.find({campaign: this._id, influencer: Meteor.userId()}).fetch();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.