从MongoDB获取分层嵌套数据

时间:2017-05-10 20:29:24

标签: mongodb mongoose mongodb-query aggregation-framework

我是MongoDB的新手。但是,我对一些aggregate函数/运算符有了解。

首先,请看一下数据(它包含板球比赛信息):

一个文档(行)如下所示:

{
    "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

那些不了解板球的人(比如我),这里的信息很少:

  • 比赛包含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 个答案:

答案 0 :(得分:1)

您可以尝试以下聚合管道。

您只需$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" } } } })

{{1}}