2016-06-24 51 views
0

我正在學習Mongodb,並試圖從Mongodb實現堆疊的highcharts。我正在努力顯示數據以匹配highcharts文檔。這是我迄今所做的:Mongodb + Stacked 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 
}] 

} 

}] 

相反,我想要以下輸出顯示高位圖:

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 

}] 

任何想法如何獲得此輸出?謝謝!

+0

如果誰可以幫我MongoDB的聚集,以獲得預期的結果? – nair

+0

不能用'categories ='和'series ='得到結果但是你可以用'map'或'forEach'方法創建所描述的結構。 https://docs.mongodb.com/manual/reference/method/cursor.map/ – AstraSerg

回答

0

您可以創建解析器,它將您的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); 
     } 
    }); 
    }); 

例子:

+0

它的工作原理 - 謝謝! – nair