2017-05-10 125 views
0

我是MongoDB中的新成員。但是,我對某些aggregate函數/運算符有所瞭解。從MongoDB獲取層次嵌套數據

首先,請看看數據(包含板球比賽的信息):

一號文件(行)看起來是這樣的:

{ 
    "ID": 577, 
    "Inning": 1, 
    "BattingTeam": "Sunrisers Hyderabad", 
    "BowlingTeam": "Royal Challengers Bangalore", 
    "Over": 1, 
    "Bowler": "S Aravind", 
    "Ball": 1, 
    "Batsman": "DA Warner", 
    "NonStriker": "S Dhawan", 
    "TotalRuns": 1 
} 
... 
... 

這裏是整個數據文件: http://raw.sam016.com/shared/match_data.json

那些誰也不知道板球(像我一樣),這裏是一點信息:

  • A匹配包含2個局[1,2]
  • 每個局包含一些接管[20,60]
  • 每過包含6個球最大

我想要聚合/組以這樣這個數據一種方式來獲得以下一種分層的結果:

[{ 
    "ID": 577, 
    "Innings": [{ 
      "Inning": 1, 
      "BattingTeam": "Sunrisers Hyderabad", 
      "BowlingTeam": "Royal Challengers Bangalore", 
      "Overs": [ 
       { 
        "Over": 1, 
        "Bowler": "S Aravind", 
        "Balls": [ 
         { 
          "Ball": 1, 
          "Batsman": "DA Warner", 
          "NonStriker": "S Dhawan", 
          "TotalRuns": 1 
         }, 
         {...}, 
         {...} 
        ] 
       }, 
       {...}, 
       {...} 
      ] 
     }, 
     { 
      "Inning": 2, 
      "BattingTeam": "Royal Challengers Bangalore", 
      "BowlingTeam": "Sunrisers Hyderabad", 
      "Overs": [ 
       { 
        "Over": 1, 
        "Bowler": "B Kumar", 
        "Balls": [ 
         { 
          "Ball": 1, 
          "Batsman": "CH Gayle", 
          "NonStriker": "V Kohli", 
          "TotalRuns": 0 
         }, 
         {...}, 
         {...} 
        ] 
       }, 
       {...}, 
       {...} 
      ] 
     } 
    ] 
}] 

任何形式的幫助,將不勝感激。

回答

1

您可以嘗試下面的聚合管道。

你剛剛在密鑰$group$push數據創建每個級別。

從最裏面的水平Balls開始,一直工作到Innings

db.cricket.aggregate({ 
    $group: { 
     "_id": { 
      "ID": "$ID", 
      "Inning": "$Inning", 
      "BattingTeam": "$BattingTeam", 
      "BowlingTeam": "$BowlingTeam", 
      "Over": "$Over", 
      "Bowler": "$Bowler" 
     }, 
     "Balls": { 
      $push: { 
       "Ball": "$Ball", 
       "Batsman": "DA Warner", 
       "NonStriker": "S Dhawan", 
       "TotalRuns": "$TotalRuns" 
      } 
     } 
    } 
}, 
{ 
    $group: { 
     _id: { 
      "ID": "$_id.ID", 
      "Inning": "$_id.Inning", 
      "BattingTeam": "$_id.BattingTeam", 
      "BowlingTeam": "$_id.BowlingTeam" 
     }, 
     "Overs": { 
      $push: { 
       "Over": "$_id.Over", 
       "Bowler": "$_id.Bowler", 
       "Balls":"$Balls" 
      } 
     } 
    } 
}, 
{ 
    $group: { 
     "_id": "$_id.ID", 
     "Innings": { 
      $push: { 
       "Inning": "$_id.Inning", 
       "BattingTeam": "$_id.BattingTeam", 
       "BowlingTeam": "$_id.BowlingTeam", 
       "Overs":"$Overs" 
      } 
     } 
    } 
}) 
+0

謝謝!!!有效。 – sam

+0

如何分類?我曾嘗試通過inning> over>球添加'$ sort'。但最終結果並未排序。 – sam

+0

您必須一次對一個級別進行排序。因此,對於第一級,您需要在推送前按'$排序'。類似於{$ sort:{Ball:1}}'在第一個$ group之前,等等其餘的級別。 – Veeram