我已使用群组汇总创建了计数数据收集的代码,但现在我遇到了进程计数组无法提供正确结果的问题。我不知道问题出在哪里。
此代码的结果与此Result类似。有我的代码:
//js
Template.laporankategori.helpers({
profilcount: function() {
var subs = {};
Profil.find().forEach(function(e) {
if (subs[e.kategori] == null)
subs[e.kategori] = 0;
subs[e.kategori] += e.amount;
});
var result = [];
_.each(subs, function(value, key) {
result.push({kategori: key, amount: value});
});
return result;
}
});
//publish
Meteor.publish("profilcount",function(args) {
var sub = this;
var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
var pipeline = [
{ "$group": {
"_id": "$kategori",
count:{$sum:amount}
}}
];
db.collection("profil").aggregate(
pipeline,
Meteor.bindEnvironment(
function(err, result) {
_.each(result, function(e) {
sub.added("profil", Random.id(), {
kategori: kategori._id,
amount: kategori.count
});
});
sub.ready();
},
function(error) {
Meteor._debug( "Error doing aggregation: " + error);
}
)
);
});
// HTML
{{#each profilcount}}
<tr>
<td>{{kategori}}</td>
<td>{{ amount}}</td>
</tr>
{{/each}}
我想要这样的结果。 Result
答案 0 :(得分:0)
我有其他解决方案,不使用聚合。以防万一它可以帮助你。
// JS
Template.laporankategori.helpers({
profilcount () {
var result = [];
var categs = [];
profil.find().forEach(function(profil) {
if(categs.indexOf(profil.kategori) > -1) {
for (var i = 0; i < result.length; i++) {
var res = result[i];
var count = res.count + 1;
var amount = res.amount + profil.amount;
result[i].count = count;
result[i].amount = amount;
break;
}
} else {
result.push({
name: profil.kategori,
amount : profil.amount,
count : 1
});
categs.push(profil.kategori);
}
});
return result;
}
});
Meteor.publish("profil",function(args) {
return profil.find({},{fields: {amount: 1, kategori:1}});
});
// HTML
<table>
<thead>
<tr>
<td> Kategori </td>
<td> Total Amount</td>
<td> Count </td>
</tr>
</thead>
<tbody>
{{#each profilcount}}
<tr>
<td>{{ name }}</td>
<td>{{ amount }}</td>
<td>{{ count }}</td>
</tr>
{{/each}}
</tbody>
</table>