Mongodb + Stacked Highcharts



我正在学习Mongodb,并试图从Mongodb实现堆叠highcharts。我正在努力显示数据以匹配highcharts文档。这是我目前所做的:

Mongodb文档:

{
    "_id" : ObjectId("576a.....b"),
    "to: "Jane",
    "mode" : "Open"
}
{
     "_id" : ObjectId("576a.....c"),
     "to: "Jane",
    "mode" : "Closed"
}
{
    "_id" : ObjectId("576a.....d"),
    "to: "Smith",
    "mode" : "Open"
}

Mongodb总:

db.collection.aggregate([
{
$group : {
    _id : {"to" : "$to", "mode": "$mode"},
    y : {$sum : 1}
}
}, {
$project : {
    "to" : "$_id.to",
    "mode" : "$_id.mode",
    "_id" : 0,
    "y" : "$y"
}
}, {
$group : {
    _id : {"to" : "$to" },
    items : {$push : {item : "$mode", qty: "$y"}}
}
}
])

我得到的输出:

[{
    "_id" : {
    "to" : "Jane"
},
"items" : [{
    "item" : "Open",
    "qty" : 1
}, {
    "item" : "Closed",
    "qty" : 1
}]
}, {
    "_id" : {
    "to" : "Smith"
},
"items" : [{
    "item" : "Open",
    "qty" : 1
}]
}
}]

相反,我希望下面的输出显示highcharts:

categories = ["Jane","Smith"]
series = [{
    name : 'Open',
    data: [1,1]  //1 -open jane, 1- open smith
}, {
    name : 'Closed',
    data : [1,0]  //1 - closed jane, 0- closed smith
}]

知道如何得到这个输出吗?谢谢!

您可以创建解析器,它将JSON从mongoDB转换为正确的格式。

var data = [{
    "_id": {
      "to": "Jane"
    },
    "items": [{
      "item": "Open",
      "qty": 1
    }, {
      "item": "Closed",
      "qty": 1
    }]
  }, {
    "_id": {
      "to": "Smith"
    },
    "items": [{
      "item": "Open",
      "qty": 1
    }]
  }];
  var outputSeries = [{
      name: 'Open',
      data: []
    }, {
      name: 'Closed',
      data: []
    }],
    each = Highcharts.each;
  each(data, function(serie, i) {
    each(serie.items, function(point, j) {
      if (point.item === 'Open') {
        outputSeries[0].data.push(point.qty);
      } else if (point.item === 'Closed') {
        outputSeries[1].data.push(point.qty);
      }
    });
  });

的例子:

  • http://jsfiddle.net/hbqfn0yr/

相关内容

  • 没有找到相关文章

最新更新