在$ push中插入两个元素,在Mongodb中插入一个$ cond

问题描述 投票:1回答:1

我在mongodb中有此查询,代表获胜球队将获得3分,而平局球队将各获得1分。


db.football.aggregate([ 
  { "$match": {
      "$and": [
        { "Div": "SP1" }
      ]
    }
  },
  { "$group": { 
      "_id": {
        "div": "$Div"
      },
      "teams": { 
        "$push": {
          "$cond": {
            "if": { "$eq": [ "$FTR", "H" ] }, 
            "then": { "T": "$HomeTeam", "P": 3 },
            "else": {
              "$cond": {
                "if": { "$eq": [ "$FTR", "A" ] }, 
                "then": { "T": "$AwayTeam", "P": 3 },
                "else": {
                  "$cond": {
                    "if": { "$eq": [ "$FTR", "D" ] }, 
                    "then": { "draws": [{ "T": "$HomeTeam", "P": 1}, { "T": "$AwayTeam", "P": 1 }] },
                    "else": "Error" 
                  }
                }
              }
            }
          }
        }
      }
    }
  }
])

导致的结果:

{ "_id" : { "div" : "SP1" }, 
          "teams" : [ 
                      { "T" : "La Coruna", "P" : 3 },
                      { "T" : "Malaga", "P" : 3 },
                      { "draws": [
                                   { "T" : "Barcelona", "P" : 1 },
                                   { "T" : "Villarreal", "P" : 1 }
                                 ]
                      },
                     ...
                    ]
}

[看到我为抽奖团队提供了一个数组,但我只想在团队中增加一个数组,如下所示:

{ "_id" : { "div" : "SP1" }, 
          "teams" : [ 
                      { "T" : "La Coruna", "P" : 3 },
                      { "T" : "Malaga", "P" : 3 },
                      { "T" : "Barcelona", "P" : 1 },
                      { "T" : "Villarreal", "P" : 1 },
                     ...
                    ]
}

我曾尝试unwind参加比赛,但效果不佳。

数据集可在此处下载:https://www.football-data.co.uk/mmz4281/1617/SP1.csv数据集信息:https://www.football-data.co.uk/notes.txt

导入csv:

mongoimport -d dataset -c football --type csv --file path_to_file_SP1.csv --headerline --drop --stopOnError
arrays mongodb aggregation-framework push
1个回答
2
投票

您可以使用$reduce展平阵列。由于您有两种不同的元素,因此可以将$cond$type结合使用,以确定是应该组合单个元素还是draws字段。

db.collection.aggregate([
    {
        $addFields: {
            teams: {
                $reduce: {
                    input: "$teams",
                    initialValue: [],
                    in: {
                        $cond: [
                            { $eq: [ { $type: "$$this.draws" }, "array" ] },
                            { $concatArrays: [ "$$value", "$$this.draws" ] },
                            { $concatArrays: [ "$$value", ["$$this"] ] }
                        ]
                    }
                }
            }
        }
    }
])

Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.