2017-09-13 63 views
0

我試圖讓我的頭在這個聚合框架,我有點卡住,我會喜歡一些幫助。如何使用已過濾的數組和已過濾的總和來聚合分組?

所以我有活動的集合,即簡化,類似這樣的已經過濾一下東西:

{ creation: 54233, eventName: "elapsedTime", userId: 1, url: "/thing/53e245ca", data: { number: 5 } }, 
{ creation: 64033, eventName: "elapsedTime", userId: 1, url: "/thing/53e245ca", data: { number: 3 } }, 
{ creation: 50298, eventName: "elapsedTime", userId: 1, url: "/thing/53e245ca", data: { number: 2 } }, 
{ creation: 74220, eventName: "toggle",  userId: 1, url: "/thing/53e245ca", data: { status: true } }, 
{ creation: 84233, eventName: "elapsedTime", userId: 2, url: "/thing/190345a9", data: { number: 8 } }, 
{ creation: 59511, eventName: "elapsedTime", userId: 2, url: "/thing/190345a9", data: { number: 10 } }, 
{ creation: 14236, eventName: "toggle",  userId: 2, url: "/thing/190345a9", data: { status: false } }, 
{ creation: 80637, eventName: "toggle",  userId: 2, url: "/thing/cc2b8b91", data: { status: true } }, 
{ creation: 99239, eventName: "toggle",  userId: 2, url: "/thing/cc2b8b91", data: { status: false } } 

我希望他們能夠聚集這樣的:

{ 
    userId: 1, 
    toggles: [ 
     { creation: 74220, url: "/thing/53e245ca", data: { status: true } } 
    ], 
    elapsedSum: 10 
}, 
{ 
    userId: 2, 
    toggles: [ 
     { creation: 14236, url: "/thing/190345a9", data: { status: false } }, 
     { creation: 80637, url: "/thing/cc2b8b91", data: { status: true } }, 
     { creation: 99239, url: "/thing/cc2b8b91", data: { status: false } }, 
    ], 
    elapsedSum: 18 
} 

所以我基本上想要按用戶分組,每個用戶擁有所有elapsedTime的總和,併爲每個用戶擁有所有toggle事件的數組。

回答

1
db.getCollection('heya').aggregate([ 
    { 
    "$group": { 
     "_id": "$userId", 
     "toogles": { 
     "$addToSet": { 
      "$cond": { 
      "if": { 
       "$eq": [ 
       "$eventName", 
       "toggle" 
       ] 
      }, 
      "then": { 
       "creation": "$creation", 
       "url": "$url", 
       "data": "$data" 
      }, 
      "else": null 
      } 
     } 
     }, 
     "elapsedSum": { 
     "$sum": { 
      "$cond": { 
      "if": { 
       "$eq": [ 
       "$eventName", 
       "elapsedTime" 
       ] 
      }, 
      "then": "$data.number", 
      "else": 0 
      } 
     } 
     } 
    } 
    } 
]) 

您可以從陣列替換空或放鬆它來獲得所需的結果

+0

哇,我不知道我怎麼沒想到這一點。這比我想象的更簡單。非常感謝你! –