我需要按降序计算所有产品,并用空格键显示它们。我该怎么办?
结果应该是:
书:2
tv:1
// My Collection
Records = new Mongo.Collection('records');
// My database
Records.insert({
name: "a", product: "book"
});
Records.insert({
name: "b", product: "tv"
});
Records.insert({
name: "c", product: "book"
});
// My Template Helper - This sorts for alphatical order
Template.foo.helpers({
'counterRecords': function(){
return Records.find({}, {sort: {product: 1}});
}});
// My Template
{{#each counterRecords}}
{{counterRecords}}: {{counterRecords.count}}
{{/each}}
答案 0 :(得分:1)
尝试一下:
Template.myTemplate.helpers({
counterRecords: function() {
var records = Records.find().fetch();
return _.chain(records).pluck('product')
.countBy()
.map(function(v, k) {return {product: k, count: v};})
.sortBy('product')
.value();
}
});
那应该产生一个像:
这样的数组[{product: 'book', count: 2}, {product: 'tv', count: 1}]
你的模板看起来像这样:
{{#each counterRecords}}
{{product}}: {{count}}
{{/each}}
答案 1 :(得分:0)
使用以下查询:
Records.aggregate(
[
{
"$group" : {
"_id" : "$product",
"count" : {
"$sum" : 1
}
}
},
{
$sort:
{
_id:1
}
}
])