2015-12-24 55 views
-1

所以我想使用Node.js驅動程序來查詢一組JSON數據。我已經看到所有使用點符號的帖子,所有這些,但我沒有得到任何地方。以下是我正在使用的數據的示例JSON。我試圖查詢阿森納所涉及的所有比賽。我沒有辦法,因爲我不太清楚如何在team1team2之下查詢該名稱(例如,如果阿森納是在team1team2)。我認爲team1,team2應該是一個數組,並且這會使事情變得更容易,但這是一個非常大的文檔,其中我不能控制,所以我不想更改結構。使用MongoDB查詢JSON中的嵌套文檔

{ 
    "_id" : ObjectId("56773d88a09bc70f31a900d5"), 
    "name" : "English Premier League 2012/13", 
    "rounds" : [ 
     { 
      "name" : "Matchday 1", 
      "matches" : [ 
       { 
        "date" : "2012-08-18", 
        "team1" : { 
         "key" : "arsenal", 
         "name" : "Arsenal", 
         "code" : "ARS" 
        }, 
        "team2" : { 
         "key" : "sunderland", 
         "name" : "Sunderland", 
         "code" : "SUN" 
        }, 
        "score1" : 0, 
        "score2" : 0 
       }, 
       { 
        "date" : "2012-08-18", 
        "team1" : { 
         "key" : "fulham", 
         "name" : "Fulham", 
         "code" : "FUL" 
        }, 
        "team2" : { 
         "key" : "norwich", 
         "name" : "Norwich", 
         "code" : "NOR" 
        }, 
        "score1" : 5, 
        "score2" : 0 
       } 
      ] 
     } 
    ] 
} 

回答

0

您可以使用$elemMatch查詢內部數組:

db.getCollection('test').find({ 
    rounds: { $elemMatch: { 
     $or: [ 
      { matches: { $elemMatch: { "team1.code": "ARS" } } }, 
      { matches: { $elemMatch: { "team2.code": "ARS" } } } 
     ] 
    } } 
}); 
0

你可以這樣做:

db.sample.aggregate(
    {$match: '...'} 
    { $unwind: '$rounds'}, 
    { $unwind: '$rounds.matches'}, 
    { $match: {'rounds.matches.team1.name': 'Arsenal'}}, 
    { $group: '...'} 
)