0

我的數據格式爲:MongoDB的聚集重塑或分組值字段名和月

[{ _id: 1, Prom: "I", date: ISOdate(2016-01-01 ...) }, 
    { _id: 2, Prom: "P", date: ISOdate(2016-01-01 ...) }, 
    { _id: 3, Prom: "D", date: ISOdate(2016-02-01 ...) }, 
    { _id: 4, Prom: "I", date: ISOdate(2016-03-01 ...) }, 
    { _id: 5, Prom: "I", date: ISOdate(2016-04-01 ...) }, 
    { _id: 6, Prom: "D", date: ISOdate(2016-04-01 ...) }, 
    { _id: 7, Prom: "P", date: ISOdate(2016-04-01 ...) }, 
    ... 
    { _id: 512, Prom: "I", date: ISOdate(2016-04-01 ...) }, 
    { _id: 632, Prom: "P", date: ISOdate(2016-06-01 ...) }, 
    { _id: 656, Prom: "I", date: ISOdate(2016-06-01 ...) }] 

我然後彙總數據來算的「P」的號碼,「我」或「d」每月像這樣:

db.Collection.aggregate([ 
{ 
    $group: { 
     _id: { Mnt:"$Mnt", Prom: "$Prom"} , 
     Count: {$sum: 1 }, 
    } 
} 
]); 

這使我的結果爲:

[{ "_id" : { "Mnt" : { "$date" : "2016-01-01T00:00:00.000+0000" }, "Prom" : "D" }, "Count" : 32 } 
{ "_id" : { "Mnt" : { "$date" : "2016-01-01T00:00:00.000+0000" }, "Prom" : "P" }, "Count" : 138 } 
{ "_id" : { "Mnt" : { "$date" : "2016-01-01T00:00:00.000+0000" }, "Prom" : "I" }, "Count" : 178 } 
{ "_id" : { "Mnt" : { "$date" : "2016-02-01T00:00:00.000+0000" }, "Prom" : "D" }, "Count" : 46 } 
{ "_id" : { "Mnt" : { "$date" : "2016-02-01T00:00:00.000+0000" }, "Prom" : "P" }, "Count" : 287 } 
{ "_id" : { "Mnt" : { "$date" : "2016-02-01T00:00:00.000+0000" }, "Prom" : "I" }, "Count" : 197 } 
    .... 
{ "_id" : { "Mnt" : { "$date" : "2016-06-01T00:00:00.000+0000" }, "Prom" : "D" }, "Count" : 55 } 
{ "_id" : { "Mnt" : { "$date" : "2016-06-01T00:00:00.000+0000" }, "Prom" : "P" }, "Count" : 42 } 
{ "_id" : { "Mnt" : { "$date" : "2016-06-01T00:00:00.000+0000" }, "Prom" : "I" }, "Count" : 14 }] 

我怎麼能組或項目該數據M來表示y格式的數據?

[{ Mnt: ISOdate(2016-01-01 ...), "P": 138, "I": 178, "D": 32 }, 
{ Mnt: ISOdate(2016-02-01 ...), "P": 287, "I": 197, "D": 46 }, 
... 
{ Mnt: ISOdate(2016-06-01 ...), "P": 42, "I": 14, "D": 55 }] 

我真的沒有找到一種方法來使用'Prom'的值作爲管道中下一個聚合的關鍵。將這個結果按月分組也是有問題的。基本上我們想要做的是按月從原始數據中創建一個Net Promoter Score,P - 發起人,D - 反對者,我 - 無動於衷。

回答

0

試試這個,

db.Collection.aggregate([ 
    { 
     $group: { 
      _id: { Mnt:"$Mnt", Prom: "$Prom"} , 
      Count: {$sum: 1 }, 
     }, 
    $group: { 
      _id:"$Mnt" ,res: { $push: "$Prom" }  
     }, 
    $project : { Mnt:$_id , res[0],res[1],res[2] 

    } 
    } 
    ]); 
+0

請考慮接受的答案,如果你有幫助。它會幫助其他同類問題。 –