计算mongodb中每个不同的值,然后渲染为amcharts

时间:2018-12-21 14:58:35

标签: angularjs mongodb mean-stack amcharts

我正在尝试从mongodb中获取每个不同值的计数,到目前为止,我可以获取不同值并对其进行计数。

我该怎么做:

City       Count
Pasig       22
Manila      12
Pasay       11

示例文档:

_id:5c1ca770385b472018874073
blood_product_donated:"Whole Blood"
branch:"Pasay"
deferral_type:"none"
deferral_date:"none"

到目前为止,这是我所做的:

api.js

router.get('/blooddonationpie', function(req, res) {
      Blooddonation.distinct('branch',function(err, branch) {      
      res.json({ success: true, branch: branch });
      console.log(branch);
   });   
});

控制器

angular.module('blooddonationControllers', [])
.controller('blooddonationCtrl', function(Blooddonation,$scope) {
var app = this;
function getChart() {

    Blooddonation.getChart().then(function(data) {
        app.branch = data.data.branch; 
        initChart();      
    });
}
function initChart() {
    var data_series = [];

    for(let key in app.branch) {
        data_series.push({
            "donor": app.branch[key],
            "count": 501.9
        });
    }

    var chart = AmCharts.makeChart( "chartdiv", {
        "type": "pie",
        "theme": "none",
        "dataProvider": data_series,
        "valueField": "count",
        "titleField": "donor",
        "balloon":{
            "fixedPosition":true
        },
        "export": {
            "enabled": true
        }
    });
}

这是错误的输出:

This is the output:

如何获取每个不同值的计数?例如Pasig:21,Pasay:22等。

1 个答案:

答案 0 :(得分:0)

您需要进行$group聚合以获取每个分支的数量

db.col.aggregate([{$group: {_id : "$branch" , count :{$sum:1}}}])