简体   繁体   中英

Querying nested documents in JSON using MongoDB

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
                }
            ]
        }
    ]
}

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" } } }
        ]
    } }
});

You can do like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM