流星集合 - 计算相同的值

Meteor collection - count same values

我需要按降序计算所有产品并用空格键显示它们。我该怎么做? 结果应该是:
书:2
电视: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}}

使用以下查询:

Records.aggregate(
[
 {
    "$group" : {
        "_id" : "$product",
        "count" : {
            "$sum" : 1
        }
    }
 },
 {
     $sort:
      {
        _id: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}}