-1

So am I trying to use the Node.js driver to query a set of JSON data. I've seen all the posts using dot notation, and all that, but I am not getting anywhere. Below is an example JSON of the data that I am working with. I am trying to query all the matches that Arsenal is involved in. I am getting nowhere since I am not too sure how to query the name under team1, or team2 for that matter (such that it will only show documents if Arsenal was in team1 or team2). I thought team1, team2 should be an array, and that would make things easier, but this is a very large document, of which I don't control, so I don't want to change the structure.

{
    "_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
                }
            ]
        }
    ]
}
StepUp
  • 36,391
  • 15
  • 88
  • 148
B. Duarte
  • 35
  • 1
  • 9

2 Answers2

0

You can use $elemMatch to query inside arrays:

db.getCollection('test').find({
    rounds: { $elemMatch: {
        $or: [
            { matches: { $elemMatch: { "team1.code": "ARS" } } },
            { matches: { $elemMatch: { "team2.code": "ARS" } } }
        ]
    } }
});
Shanoor
  • 13,344
  • 2
  • 29
  • 40
0

You can do like this:

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