队
我正在使用mongodb和spring数据。
我从mongodb到聚合(组)得到了一些结果。现在我想通过json数组将多行组转换为单个json文档,如下所示
FROM:
{ "count" : 8, "SERVICE" : "ABC", "BUCKET" : "1", "TIME" : "16100106" }
{ "count" : 8, "SERVICE" : "ABC", "BUCKET" : "1", "TIME" : "16100107" }
{ "count" : 8, "SERVICE" : "ABC", "BUCKET" : "2", "TIME" : "16100108" }
{ "count" : 10, "SERVICE" : "XYZ", "BUCKET" : "1", "TIME" : "16100106" }
{ "count" : 10, "SERVICE" : "XYZ", "BUCKET" : "1", "TIME" : "16100107" }
{ "count" : 10, "SERVICE" : "XYZ", "BUCKET" : "2", "TIME" : "16100108" }
TO:
{
"ABC" : { //SERVICE
1: { //BUCKET
16100106 : 8, //TIME:count
16100107 : 8
},
2: {
16100108 : 8
},
},
"XYZ" : {
1: {
16100106 : 10,
16100107 : 10
},
2: {
16100108 : 10
},
}
}
复杂性:
列数将更改(在$ groupby / $项目中添加新列)
应该能够通过订单,当前示例显示的顺序如
SERVICE --> BUCKET --> TIME --> count
,
但这应该像
一样可以改变 TIME --> BUCKET --> SERVICE --> count
因此寻找支持这个的任何通用库?或任何建议?
答案 0 :(得分:0)
我是使用Stack Overflow的新手,我很高兴为了得到一个灵感而贡献我的想法。
我不知道它如何与mongodb一起工作,但是如果你使用node.js,你可以使用Array扩展一个函数,就像这样
Array.prototype.converGroupToSingle = function(){
var r = {}
this.forEach(function(s){
//not have SERVICE
;(r[s.SERVICE] || (r[s.SERVICE] = {[s.BUCKET]:{[s.TIME]:s.count}},false))
//have SERIVCE
&& (
// not have BUCKET
(r[s.SERVICE][s.BUCKET] || (r[s.SERVICE][s.BUCKET] = {[s.TIME]:s.count},false))
//have BUKCET but not have TIME
&& (r[s.SERVICE][s.BUCKET][s.TIME] || (r[s.SERVICE][s.BUCKET][s.TIME] = s.count,false))
)
})
return r
}
并使用它,就像这样
var arrGroup = [
{ "count" : 8, "SERVICE" : "ABC", "BUCKET" : "1", "TIME" : "16100106" }
,{ "count" : 8, "SERVICE" : "ABC", "BUCKET" : "1", "TIME" : "16100107" }
,{ "count" : 8, "SERVICE" : "ABC", "BUCKET" : "2", "TIME" : "16100108" }
,{ "count" : 10, "SERVICE" : "XYZ", "BUCKET" : "1", "TIME" : "16100106" }
,{ "count" : 10, "SERVICE" : "XYZ", "BUCKET" : "1", "TIME" : "16100107" }
,{ "count" : 10, "SERVICE" : "XYZ", "BUCKET" : "2", "TIME" : "16100108" }
]
var singleGroup = arrGroup.converGroupToSingle()
如果你输出singleGroup
,就像这样
// the singleGroup
{
ABC:
{
'1': { '16100106': 8, '16100107': 8 },
'2': { '16100108': 8 }
},
XYZ:
{
'1': { '16100106': 10, '16100107': 10 },
'2': { '16100108': 10 }
}
}
希望它可以帮到你。
感谢。