在谷歌图表中显示MongoDB结果

display mongodb result in a google chart

本文关键字:显示 MongoDB 结果 谷歌      更新时间:2023-09-26

我有一个MongoDB集合,其中包含一些商店的点击项目。如果有人单击某个项目,数据库将添加以下格式的 json:

{ 
"_id" : { "$oid" : "56cf06ce0b7707c83e5a8c64" }, 
"date" : { "$date" : 1456408270811 }, 
"name" : "Jura whisky", 
"store" : "56c9bfed942693bb745229ef" 
}

因此,数据库具有不同的项目,具有不同商店的不同日期。如果我想获取特定商店所有商品的所有点击次数,我使用此查询:

var id = global.actuallUser._doc._id;
            id = id.toString();
            global.databaseStatistic.collection(global.ARTICLEPRESS).aggregate(
                    [
                        {$match: {
                                $and: [
                                    {
                                        store: id,
                                        date: {
                                            $gte: new Date('12/01/2013'),
                                            $lte: new Date('12/01/2017')
                                        }
                                    }
                                ]
                            }},
                        {$group: {"_id": {name: "$name", day: {$dayOfMonth: "$date"},month: {$month: "$date"},year: {$year: "$date"}}, "count": {$sum: 1}}}
                    ]
                    ).toArray(function (err, result) {
                res.send(result);
            });

现在,我得到了一个对象数组,其属性为 Name, day....是否可以以这种格式获得此结果:

['date', 'name', 'count'],
['1.1.2000', Jura whisky, 400],
['1.1.2000', Potato, 460],
['1.1.2000', Pizza, 1120],
['2.1.2000', Jura whisky, 540]

所以我可以用谷歌图表 API 制作数据图表。

谢谢!

假设你results JSON 对象作为 ajax 调用的结果。

var columns = Object.keys(results[0]);
var data = results.map(function (result) {
  var tableRow = [];
  columns.forEach(function (col) {
    tableRow.push(result[col]);
  });
  return tableRow;
});

data将包含要由谷歌图表呈现的表格行。

var dataTable = new google.visualization.DataTable();
columns.forEach(function (columnName) {
  dataTable.addColumn(columnName);
});
dataTable.addRows(data);