在mongo中过滤内部数组

时间:2019-02-11 21:30:54

标签: mongodb mongodb-query aggregation-framework

基本上,我正在尝试按内部数组中的给定字段进行过滤。

"_id" : ObjectId("5c5f410990663d5ab5ee3871"),
"Year" : 1986,
"Datetime" : "29 Jun 1986 - 12:00 ",
"Stage" : "Final",
"Stadium" : "Estadio Azteca",
"City" : "Mexico City ",
"Home Team Name" : "Argentina",
"Home Team Goals" : 3,
"Away Team Goals" : 2,
"Away Team Name" : "Germany FR",
"Win conditions" : "NA",
"Attendance" : 114600,
"Half-time Home Goals" : 1,
"Half-time Away Goals" : 0,
"Referee" : "ARPPI FILHO Romualdo ",
"Referee_Nationality" : "BRA",
"Assistant 1" : "FREDRIKSSON Erik ",
"Assistant_1_Nationality" : "SWE",
"Assistant 2" : "ULLOA MORERA Berny ",
"Assistant_2_Nationality" : "CRC",
"RoundID" : 3467,
"MatchID" : 393,
"Home Team Initials" : "ARG",
"Away Team Initials" : "FRG",
"MatchPlayedBy" : [
    {
        "_id" : ObjectId("5c5f2a4c90663d5ab5edd521"),
        "RoundID" : 3467,
        "MatchID" : 393,
        "Team Initials" : "FRG",
        "Coach Name" : "BECKENBAUER Franz (GER)",
        "Line-up" : "S",
        "Shirt Number" : 1,
        "Player Name" : "Harald SCHUMACHER",
        "Position" : "GK",
        "Event" : "NA"
    },
    {
        "_id" : ObjectId("5c5f2a4c90663d5ab5edd523"),
        "RoundID" : 3467,
        "MatchID" : 393,
        "Team Initials" : "FRG",
        "Coach Name" : "BECKENBAUER Franz (GER)",
        "Line-up" : "S",
        "Shirt Number" : 4,
        "Player Name" : "Karl Heinz FOERSTER",
        "Position" : "NA",
        "Event" : "NA"
    },
    {

db.WorldCupFinals.aggregate([
    {$match : { $and :[{"Year" : {$eq:2014}}, {"MatchPlayedBy.Team Initials" : "ARG"}]}}
])

结果只能是阿根廷国家队的球员

1 个答案:

答案 0 :(得分:1)

如果要对嵌套数组应用过滤条件,则应使用$filter,请尝试:

db.WorldCupFinals.aggregate([
    { $match: { Year: 2014 } },
    {
        $addFields: {
            MatchPlayedBy: { $filter: { input: "$MatchPlayedBy", cond: { $eq: [ "$$this.Team Initials", "ARG" ] } } }
        }
    }
])

$addFields将仅使用过滤后的值覆盖现有数组